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"),组)
原始数据框:
日期组1 2018-11-28 A2 2018-12-17乙3 2019-01-23 C
我想要一个数据框,该数据框将日期扩展到下一个列,但仍保留组信息.例如,日期2018年11月28日至2018年12月16日在A组中,日期2018年12月17日至2019年1月22日在B组中,2019年1月23日在C组中./p>
这是我想要的输出( result_df
):
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
)来解决此问题.
先谢谢了.
首先,确保将 date
存储为日期对象:
demo_df $ date<-as.Date(demo_df $ date,format =%Y-%m-%d")
然后使用 tidyverse
,我们首先完成
该序列,然后填充
该组:
库(tidyverse)demo_df%&%;%complete(date = seq.Date(min(date),max(date),by ="day"))%>%填充(igroup)
I have the raw data frame:
igroup=c("A", "B", "C")
demo_df=data.frame(date=c("2018-11-28", "2018-12-17", "2019-01-23"), group)
Raw data frame:
date group
1 2018-11-28 A
2 2018-12-17 B
3 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.
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
I am wondering if there is any more efficient way (using dplyr
) to handle this issue.
Thanks in advance.
First, make sure date
is stored as a date object:
demo_df$date <- as.Date(demo_df$date, format = "%Y-%m-%d")
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屋!