R 将值保留到第一条记录
使用此示例:R 将值保留到第一条记录,r,R,使用此示例: 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
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")
library(dplyr)
dframe1 <- mutate(dframe1, date = as.Date(date))
dframe2 <- mutate(dframe2, date = as.Date(date))
df2 <-
dframe2 %>%
group_by(id, date) %>%
summarise(text_sth = paste(text_sth, collapse = " "))
left_join(dframe1, df2, by = "id") %>%
mutate(date_diff = as.numeric(date.y - date.x)) %>%
filter(abs(date_diff) == 1) %>%
mutate(label = ifelse(date_diff == -1, "before", "after")) %>%
select(id, name, label, text_sth)
dframe1%
变异(标签=ifelse(日期差异==-1,“之前”,“之后”))%>%
选择(id、名称、标签、文本)
可以在特定日期范围的特定时间之前和之后保存数据
如何根据dframe1中的特定时间修改它并将数据保留在日期之前?您正在根据不在数据框中的列进行筛选。每行应该有一个条件语句,如果df2和dframe1的长度不相同,那么情况就不是这样了,您想要的最终结果应该是什么样子?您能否编辑您的问题并提供有关示例数据最终结果的信息?