R — Expand date range into panel data by group

后端 未结 2 1394
名媛妹妹
名媛妹妹 2021-01-22 13:22

I have date ranges that are grouped by two variables (id and type) that are currently stored in a data frame called data. My goal is to ex

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 14:03

    1) by Here is a three line answer using by from the base of R. First we convert the dates to "Date" class giving data2. Then we apply f which does the real work over each row and finally we rbind the resulting rows together:

    data2 <- transform(data, from = as.Date(from), to = as.Date(to))
    
    f <- function(x) with(x, data.frame(id, type, date = seq(from, to, by = "day")))
    do.call("rbind", by(data, 1:nrow(data), f))
    

    2) data.table Using the same data2 with data.table we do it like this:

    library(data.table)
    
    dt <- data.table(data2)
    dt[, list(id, type, date = seq(from, to, by = "day")), by = 1:nrow(dt)]
    

    2a) data.table or alternately this where dt is from (2) and f is from (1):

    dt[, f(.SD), by = 1:nrow(dt)]
    

    3) dplyr with dplyr it gives a warning but otherwise works where data2 and f are from (1):

    data2 %>% rowwise() %>% do(f(.))
    

    UPDATES Some improvements.

提交回复
热议问题