Храните записи до и после определенной отметки времени - PullRequest
0 голосов
/ 31 октября 2019

Наличие фрейма данных, который предоставляет определенную временную метку

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

Вот что я попробовал

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)))

Из dframe1 есть идентификаторы, которые совпадают с dframe2. Используя дату frame1 для каждого идентификатора, я хочу сохранить для каждого пользователя его / ее активность за один день до и один день после даты dframe1. И, наконец, создайте фрейм данных, который содержит идентификатор, текстовый столбец слияния, имя dframe1 и метку до и после которой - это один день до и один день после даты dframe1

1 Ответ

2 голосов
/ 31 октября 2019
  1. Преобразование строк даты в фактические даты.
library(dplyr)

dframe1 <- mutate(dframe1, date = as.Date(date))
dframe2 <- mutate(dframe2, date = as.Date(date))
Свернуть значения text_sth внутри каждой группы id, date в dframe2. Они все равно появятся вместе на выходе.
df2 <- 
  dframe2 %>% 
  group_by(id, date) %>% 
  summarise(text_sth = paste(text_sth, collapse = " "))

df2
#> # A tibble: 10 x 3
#> # Groups:   id [2]
#>       id date       text_sth                              
#>    <int> <date>     <chr>                                 
#>  1     1 2008-10-31 another text other                    
#>  2     1 2008-11-01 test text_sth                         
#>  3     1 2008-11-02 another one test text_sth another text
#>  4     1 2008-11-03 other                                 
#>  5     1 2008-11-04 text here                             
#>  6     1 2008-11-05 text here                             
#>  7     2 2008-10-31 etc                                   
#>  8     2 2008-11-01 test text_sth                         
#>  9     2 2008-11-02 text here another text                
#> 10     2 2008-11-03 text here
Все остальное: объедините по id, оставьте только те строки, в которых разница между датой первого df и датой второго df равна 1 или -1. В зависимости от знака заполните переменную label.
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)
#>    id   name  label                               text_sth
#> 1   1 Google before                     another text other
#> 2   1 Google  after another one test text_sth another text
#> 3   1  Yahoo before                     another text other
#> 4   1  Yahoo  after another one test text_sth another text
#> 5   1 Amazon before                                  other
#> 6   1 Amazon  after                              text here
#> 7   2 Amazon before                                    etc
#> 8   2 Amazon  after                 text here another text
#> 9   2 Google before                          test text_sth
#> 10  2 Google  after                              text here
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...