insert rows between dates by group

前端 未结 6 1799
半阙折子戏
半阙折子戏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 03:12

    We can use the tidyverse to achieve this task.

    library(tidyverse)
    
    dt2 <- dt %>%
      group_by(user) %>%
      do(date = seq(from = min(.$date), to = max(.$date), by = 1)) %>%
      unnest() %>%
      left_join(dt, by = c("user", "date")) %>%
      replace_na(list(dummy = 0)) %>%
      select(colnames(dt))
    
    dt2
    # A tibble: 9 x 3
        user dummy       date
            
    1      A     1 2017-01-03
    2      A     0 2017-01-04
    3      A     0 2017-01-05
    4      A     1 2017-01-06
    5      B     1 2016-05-01
    6      B     0 2016-05-02
    7      B     1 2016-05-03
    8      B     0 2016-05-04
    9      B     1 2016-05-05
    

提交回复
热议问题