I have a dataframe
       Date      repair     
 <date>           <dbl>        
 2018-07-01        4420    
 2018-07-02          NA   
 2018-07-03          NA
 2018-07-04          NA
 2018-07-05          NA
Where 4420 is time in minutes. I'm trying to get this:
       Date      repair     
 <date>           <dbl>        
 2018-07-01        1440    
 2018-07-02        1440   
 2018-07-03        1440
 2018-07-04         100
 2018-07-05          NA
Where 1440 - minutes in one day and 100 what is left. I made it with loop. Can this be achieved in a more elegant way?
With dplyr:
library(dplyr)
df %>%
  mutate(
    repair = c(rep(1440, floor(repair[1] / 1440)), 
               repair[1] %% 1440, 
               rep(NA, n() - length(c(rep(1440, floor(repair[1] / 1440)), repair[1] %% 1440))))
  )
Output:
        Date repair
1 2018-07-01   1440
2 2018-07-02   1440
3 2018-07-03   1440
4 2018-07-04    100
5 2018-07-05     NA
You could write a little function for that task
f <- function(x, y, length_out) {
  remainder <- x %% y 
  if(remainder == 0) {
    `length<-`(rep(y, x %/% y), length_out)
  } else {
    `length<-`(c(rep(y, x %/% y), remainder), length_out)
  }
}
Input
x <- 4420
y <- 24 * 60
Result
f(x, y, length_out = 10)
# [1] 1440 1440 1440  100   NA   NA   NA   NA   NA   NA
length_out should probably be equal to nrow(your_data) 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With