Having a data frame which provides a specific timestamp
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))
And a second one from which I would like to keep info before and after the specific time from the first dataframe
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")
How is it possible to have this output?
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 is what I tried
library(dplyr)
dframe1 %>%
mutate(date = as.Date(date), date1 = date) %>%
group_by(id) %>%
tidyr::complete(date1 = seq(date1 - 1, date1 + 1, by = "1 day")) %>%
filter(date1 != date | is.na(date)) %>%
select(-date) %>%
mutate(col = c("before", "after")) %>%
rename(date = 3) %>%
inner_join(dframe2 %>% mutate(date = as.Date(date)))
From dframe1 there are ids which are the same with dframe2. Using the frame1 date for every id I want to keep for every user his/her activity one day before and one day after the date of dframe1. And finally create a dataframe which contains id, merge text column, the name of dframe1 and a labeling before and after which is the one day before and the one day after date of dframe1