现在,我的数据集具有较宽的格式,这意味着我每人有一行,但是我想要一个长数据集,每人有多行。我有两个日期变量ADATE和DDATE,分别想用作我的起点和终点。例如,如果某人的ADATE是02/04/10,而DDATE是02/07/10,则我需要4行:
拥有:
ID ADATE DDATE
1 02/04/10 02/07/10
想要:
ID ADATE DDATE NEW_DATE
1 02/04/10 02/07/10 02/04/10
1 02/04/10 02/07/10 02/05/10
1 02/04/10 02/07/10 02/06/10
1 02/04/10 02/07/10 02/07/10
我要为此执行多个数据集,并且我编写了适用于除单个数据集外的每个数据集的代码...我不确定为什么。这是我的尝试,也是我得到的错误:
jan15_long <- chf_jan15 %>%
mutate(NEW_DATE = as.Date(ADATE)) %>%
group_by(ID) %>%
complete(NEW_DATE = seq.Date(as.Date(ADATE), as.Date(DDATE), by = "day")) %>%
fill(vars) %>%
ungroup()
Error in seq.Date(as.Date(ADATE), as.Date(DDATE), by = "day") :
'from' must be of length 1
上面的代码给了我我想要的,并且可以完美地运行于我拥有的所有其他数据集(11个中的10个)。
有更好的方法吗? dplyr
对我来说最有意义,因此希望对此有解决方案。
答案 0 :(得分:2)
如果有多于一行,则需要循环seq
。我们可以使用map2
。此外,根据“日期”列的format
,as.Date
需要一个format
参数,即as.Date(ADATE, "%m/%d/%y")
(假设它是月/日/年格式)>
library(dplyr)
library(purrr)
library(lubridate)
chf_jan15 %>%
mutate_at(vars(ends_with("DATE")), mdy) %>%
mutate(random_date = map2(ADATE, DDATE, seq, by = "day")) %>%
unnest(c(random_date))
# A tibble: 4 x 4
# ID ADATE DDATE random_date
# <int> <date> <date> <date>
#1 1 2010-02-04 2010-02-07 2010-02-04
#2 1 2010-02-04 2010-02-07 2010-02-05
#3 1 2010-02-04 2010-02-07 2010-02-06
#4 1 2010-02-04 2010-02-07 2010-02-07
如果只有一行,则转换为Date
类后,complete
应该可以工作
library(tidyr)
chf_jan15 %>%
mutate_at(vars(ends_with("DATE")), as.Date, format = "%m/%d/%y") %>%
mutate(NEW_DATE = ADATE) %>%
complete(NEW_DATE = seq(ADATE, DDATE, by = 'day')) %>%
fill(c(ID, ADATE, DDATE))
# A tibble: 4 x 4
# NEW_DATE ID ADATE DDATE
# <date> <int> <date> <date>
#1 2010-02-04 1 2010-02-04 2010-02-07
#2 2010-02-05 1 2010-02-04 2010-02-07
#3 2010-02-06 1 2010-02-04 2010-02-07
#4 2010-02-07 1 2010-02-04 2010-02-07
如果每个“ ID”都有一行,那么我们可以group_split
并使用complete
chf_jan15 %>%
mutate_at(vars(ends_with("DATE")), as.Date, format = "%m/%d/%y") %>%
mutate(NEW_DATE = ADATE) %>%
group_split(ID) %>%
map_dfr(~ .x %>%
complete(NEW_DATE = seq(ADATE, DDATE, by = 'day')) %>%
fill(c(ID, ADATE, DDATE)))
chf_jan15 <- structure(list(ID = 1L, ADATE = "02/04/10",
DDATE = "02/07/10"), class = "data.frame", row.names = c(NA,
-1L))