insert rows between dates by group

前端 未结 6 1814
半阙折子戏
半阙折子戏 2021-02-10 02:42

I want to insert rows between two dates by group. My way of doing it is so complicated that I insert missing values by last observation carry forwards and then merge. I was wond

6条回答
  •  爱一瞬间的悲伤
    2021-02-10 03:13

    A Base R (not quite as elegant) solution:

    # Data
    user<-c("A","A","B","B","B") 
    dummy<-c(1,1,1,1,1)
    date<-as.Date(c("2017/1/3","2017/1/6","2016/5/1","2016/5/3","2016/5/5"))
    df1 <-data.frame(user,dummy,date)
    
    # Solution
    do.call(rbind, lapply(split(df1, df1$user), function(df) {
      dff <- data.frame(user=df$user[1], dummy=0, date=seq.Date(min(df$date), max(df$date), 'day'))
      dff[dff$date %in% df$date, "dummy"] <- df$dummy[1]
      dff
    }))
    
    
    # user dummy date      
    # A    1     2017-01-03
    # A    0     2017-01-04
    # A    0     2017-01-05
    # A    1     2017-01-06
    # B    1     2016-05-01
    # B    0     2016-05-02
    # B    1     2016-05-03
    # B    0     2016-05-04
    # B    1     2016-05-05
    

提交回复
热议问题