insert rows between dates by group

前端 未结 6 1801
半阙折子戏
半阙折子戏 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 02:59

    By using dplyr and tidyr :)(one line solution )

    library(dplyr)
    library(tidyr)
    dt %>% group_by(user) %>% complete(date=full_seq(date,1),fill=list(dummy=0))
    # A tibble: 9 x 3
    # Groups:   user [2]
        user       date dummy
            
    1      A 2017-01-03     1
    2      A 2017-01-04     0
    3      A 2017-01-05     0
    4      A 2017-01-06     1
    5      B 2016-05-01     1
    6      B 2016-05-02     0
    7      B 2016-05-03     1
    8      B 2016-05-04     0
    9      B 2016-05-05     1
    

提交回复
热议问题