使用日期之前和之后将记录基于另一个记录保存到一个数据框中

时间:2019-09-27 16:15:29

标签: 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))

第二个:

    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"
), name = c("Google", "Yahoo", "Amazon", "Google", "Yahoo", "Amazon", 
"Google", "Yahoo", "Amazon", "Google", "Yahoo", "Amazon", "Google", 
"Amazon", "Google", "Amazon", "Google"), 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")), class = "data.frame", row.names = c(NA, 
-17L))

使用dframe1的结果,如何从dataframe2中保留每个ID与dframe1相同名称但在dframe1记录日期之前和之后的日期的行?

这是我尝试过的

library(data.table)
library(tidyverse)
library(reshape2)

dframe1 = data.table(dframe1)
dframe1[, date := as.Date(date)]

dframe1_first = dframe1[, .(date = min(date)), .(id, name)] %>% 
    mutate(date_pre = date - 1,
           date_after = date + 1)

req_rows = dframe2 %>%
    merge(dframe1_first %>%
              rename(id = id),
          by = "id") %>%
    filter(date >= date_pre,
           date <= date_after,
           date != date) %>%
    mutate(period = ifelse(date<date, '1-day-pre', '1-day-after'))

预期输出:

 id       date   name     text_sth
1 2008-10-31 Google another text
1 2008-10-31  Yahoo        other
1 2008-11-02 Google         test
1 2008-11-02  Yahoo     text_sth
1 2008-11-05 Amazon    text here
1 2008-11-02 Google another text
2 2008-10-31 Amazon          etc
2 2008-11-01 Google         test
2 2008-11-02 Amazon another text
2 2008-11-03 Google    text here

0 个答案:

没有答案