【发布时间】:2019-11-02 00:02:44
【问题描述】:
拥有一个提供特定时间戳的数据框
dframe1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L), name = c("Google",
"Yahoo", "Amazon", "Amazon", "Google"), date = c("2008-11-01",
"2008-11-01", "2008-11-04", "2008-11-01", "2008-11-02")), class = "data.frame", row.names = c(NA,
-5L))
第二个我想在第一个数据帧的特定时间前后保留信息
dframe2 <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L), date = c("2008-11-01", "2008-11-01",
"2008-11-04", "2008-10-31", "2008-10-31", "2008-11-02", "2008-11-02",
"2008-11-02", "2008-11-05", "2008-11-02", "2008-11-03", "2008-10-31",
"2008-11-01", "2008-11-01", "2008-11-02", "2008-11-02", "2008-11-03"
), text_sth = c("test", "text_sth", "text here", "another text",
"other", "another one", "test", "text_sth", "text here", "another text",
"other", "etc", "test", "text_sth", "text here", "another text",
"text here")), row.names = c(NA, -17L), class = "data.frame")
怎么可能有这个输出?
id text_sth name label
1 another text other Google before
1 another one test text_sth another text Google after
1 another text other Yahoo before
1 another one test text_sth another text Yahoo after
1 other Amazon before
1 text here Amazon after
使用此代码,它仅在找到时间戳前后两天时才保留结果。即使之前和之后的时间戳不存在但之前的所有日子都存在,如何更改它并使其保持到前后两天?来自here
left_join(dframe1, df2, by = "id") %>%
mutate(date_diff = as.numeric(date.y - date.x)) %>%
filter(abs(date_diff) == 2) %>%
mutate(label = ifelse(date_diff == -2, "before", "after")) %>%
select(id, name, label, text_sth)
【问题讨论】:
标签: r