Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread an integer over several rows as many times as it is divided by a constant

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?

like image 402
Dmytro Fedoriuk Avatar asked Feb 06 '19 13:02

Dmytro Fedoriuk


2 Answers

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
like image 78
arg0naut91 Avatar answered Oct 06 '22 05:10

arg0naut91


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)

like image 28
markus Avatar answered Oct 06 '22 05:10

markus