R:按日期依次展开和填充数据框 [英] R: expand and fill data frame by date in series
问题描述
我有原始数据框:
igroup=c("A", "B", "C")
demo_df=data.frame(date=c("2018-11-28", "2018-12-17", "2019-01-23"), group)
原始数据框:
date group
1 2018-11-28 A
2 2018-12-17 B
3 2019-01-23 C
我想要一个将日期扩展到下一列但仍保留组信息的数据框.例如,2018-11-28 至 2018-12-16 为 A 组,2018-12-17 至 2019-01-22 为 B 组,2019-01-23 为 C 组.
I want to have a data frame that expand the date to next column but still keep the group information. For example, date from 2018-11-28 to 2018-12-16 is with group A, date from 2018-12-17 to 2019-01-22 is with group B and 2019-01-23 is with group C.
这是我想要的输出 (result_df
):
This is the output (result_df
) I want:
time=c(seq(as.Date("2018-11-28"), as.Date("2018-12-17")-1, by=1),
seq(as.Date("2018-12-17"), as.Date("2019-01-23")-1, by=1),as.Date("2019-01-23") )
group1=c(rep("A",as.numeric(as.Date("2018-12-17")-as.Date("2018-11-28"))),
rep("B",as.numeric(as.Date("2019-01-23")-as.Date("2018-12-17"))), "C" )
result_df=data.frame(time,group1 )
result_df
我想知道是否有更有效的方法(使用 dplyr
)来处理这个问题.
I am wondering if there is any more efficient way (using dplyr
) to handle this issue.
提前致谢.
推荐答案
首先,确保将 date
存储为日期对象:
First, make sure date
is stored as a date object:
demo_df$date <- as.Date(demo_df$date, format = "%Y-%m-%d")
然后使用tidyverse
,我们先完成
序列,然后填充
组:
Then using tidyverse
, we first complete
the sequence, then fill
the group down:
library(tidyverse)
demo_df %>% complete(date = seq.Date(min(date), max(date), by = "day")) %>%
fill(igroup)
这篇关于R:按日期依次展开和填充数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!