给定开始日期和结束日期,reshape/expand 之间每一天的数据(连续每一天)

Given start date and end date, reshape/expand data for each day between (each day on a row)

我花了很多时间在 R 中得到每个不同的日子:

start <- as.Date(c("2013-02-26", "2013-03-26","2013-04-01","2013-04-26","2013-05-26"))
end <- as.Date(c("2013-03-25","2013-03-31","2013-04-25","2013-05-25","2013-06-25"))
per_cost <- c(3451380,3767052,3726900,4076868,3575311)
x    <- data.frame(START_DAY=start, END_DAY=end, PER_COST=per_cost) 
x$DIF_DAYS<- x$END_DAY-x$START_DAY

然后,我得到了这个:

    START_DAY    END_DAY PER_COST DIF_DAYS
1 2013-02-26 2013-03-25  3451380  27 days
2 2013-03-26 2013-03-31  3767052   5 days
3 2013-04-01 2013-04-25  3726900  24 days
4 2013-04-26 2013-05-25  4076868  29 days
5 2013-05-26 2013-06-25  3575311  30 days

我想得到这个输出:

DATE        PER_COST
2013-02-26 3451380
2013-02-27 3451380
2013-02-28 3451380
2013-02-29 3451380
...
2013-03-25 3451380
2013-03-26 3767052
2013-03-27 3767052
2013-03-28 3767052

如何操作?

你可以这样做

do.call(rbind, apply(df, 1, function(x) 
  data.frame(DATE = seq.Date(from = as.Date(x[1]), to = as.Date(x[2]), by = "day"), 
             PER_COST = x[3], row.names = NULL))
)
# 1.1  2013-02-26  3451380
# 1.2  2013-02-27  3451380
# 1.3  2013-02-28  3451380
# 1.4  2013-03-01  3451380
# 1.5  2013-03-02  3451380
# 1.6  2013-03-03  3451380
# 1.7  2013-03-04  3451380

使用data.table

library(data.table)
setDT(x)[, list(DATE=seq(START_DAY, END_DAY, by = 'day')), PER_COST]
#    PER_COST       DATE
# 1:  3451380 2013-02-26
# 2:  3451380 2013-02-27
# 3:  3451380 2013-02-28
# 4:  3451380 2013-03-01
# 5:  3451380 2013-03-02
#---                    
#116:  3575311 2013-06-21
#117:  3575311 2013-06-22
#118:  3575311 2013-06-23
#119:  3575311 2013-06-24
#120:  3575311 2013-06-25

如果有重复的PER_COST,那么用1:nrow(x)作为分组变量可能会更好

setDT(x)[, list(DATE=seq(START_DAY, END_DAY, by = 'day'), 
      PER_COST=rep(PER_COST, END_DAY-START_DAY+1)), 1:nrow(x)]

更新

使用dplyr

library(dplyr)
  x %>% 
    rowwise() %>% 
    do(data.frame(DATE=seq(.$START_DAY, .$END_DAY, by='day'),
       PER_COST= rep(.$PER_COST, .$END_DAY-.$START_DAY+1)))