我有一系列事件,其开始日期和结束日期:
library(lubridate)
df<-tibble(StartDate=ymd_hm(c("2018-01-01 00:10","2018-01-02 00:20","2018-01-05 08:20"),tz="EET"),
EndDate=ymd_hm(c("2018-01-01 00:10","2018-01-02 01:30","2018-01-05 08:30"),tz="EET"),
Event=c("Event1","Event2","Event3"))
对于每个事件,我希望所有10分钟都出现。我可以使用循环和列表来做到这一点:
DateTime=list()
Event=list()
for (i in 1:nrow(df)){
DateTime[[i]]<-seq(df$StartDate[i],df$EndDate[i],by="10 min")
Event[[i]]<-rep(df$Event[i],times=length(DateTime[[i]]))
}
result<-tibble(DateTime=do.call("c",DateTime),Event=do.call("c",Event))
所需的输出:
> result
# A tibble: 11 x 2
DateTime Event
<dttm> <chr>
1 2018-01-01 00:10:00 Event1
2 2018-01-02 00:20:00 Event2
3 2018-01-02 00:30:00 Event2
4 2018-01-02 00:40:00 Event2
5 2018-01-02 00:50:00 Event2
6 2018-01-02 01:00:00 Event2
7 2018-01-02 01:10:00 Event2
8 2018-01-02 01:20:00 Event2
9 2018-01-02 01:30:00 Event2
10 2018-01-05 08:20:00 Event3
11 2018-01-05 08:30:00 Event3
但是我正在寻找一种更精致的方法,也许使用tidyverse函数。
请注意,您可能需要更改系统时区的“ EET”,才能完全重现该示例。
谢谢
答案 0 :(得分:4)
一种选择是使用unnest
获取“ StartDate”和“ EndDate”的相应元素之间的顺序,然后执行library(tidyverse)
df %>%
transmute(DateTime = map2(StartDate, EndDate, seq, by = "10 min"),
Event) %>%
unnest %>%
select(DateTime, Event)
# A tibble: 11 x 2
# DateTime Event
# <dttm> <chr>
# 1 2018-01-01 00:10:00 Event1
# 2 2018-01-02 00:20:00 Event2
# 3 2018-01-02 00:30:00 Event2
# 4 2018-01-02 00:40:00 Event2
# 5 2018-01-02 00:50:00 Event2
# 6 2018-01-02 01:00:00 Event2
# 7 2018-01-02 01:10:00 Event2
# 8 2018-01-02 01:20:00 Event2
# 9 2018-01-02 01:30:00 Event2
#10 2018-01-05 08:20:00 Event3
#11 2018-01-05 08:30:00 Event3
concat()