This question already has answers here:
Expand rows by date range using start and end date

(5个答案)


3年前关闭。





我花了很多时间来获得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


怎么做?

最佳答案

使用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)))

08-20 00:07