Сохранять строки до определенной временной отметки, даже если последняя не существует - PullRequest
0 голосов
/ 02 ноября 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

Используя этот код, он сохраняет результаты, только если он находит два дня до и после отметок времени. Как можно изменить его и сохранить до двух дней до и после, даже если отметки времени до и после не существуют, но существуют все предыдущие дни до этого? С здесь

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)

1 Ответ

1 голос
/ 02 ноября 2019

в следующий раз, возможно, укажите свой предыдущий пост и включите соответствующие биты кода, поэтому, например, вам необходимо сначала преобразовать данные (как ранее)

dframe1$date = as.Date(dframe1$date)
dframe2$date = as.Date(dframe2$date)

Такиспользуя то, что @IaroslavDomin предоставил, вам нужно изменить фильтр. То, что я делаю здесь, немного отличается от его. Я использую dframe2 напрямую.

X = left_join(dframe1, dframe2, by = "id") %>% 
  mutate(date_diff = as.numeric(date.y - date.x)) %>%
  # change the filter here, >0 means not the same
  # < 2 means within 2 days 
  filter(abs(date_diff)>0 & abs(date_diff)<2 ) %>% 
  mutate(label = ifelse(date_diff <0, "before", "after")) %>% 
  select(id, name, label, text_sth)

Теперь у нас есть текст с метками. Мы группируем их и даем правильную метку

X= X %>% group_by(id,name,label) %>%
summarize(test=paste(unique(text_sth),collapse=" "))

Если мы возглавляем финальный стол:

# A tibble: 10 x 4
# Groups:   id, name [5]
      id name   label  test                                  
   <int> <chr>  <chr>  <chr>                                 
 1     1 Amazon after  text here                             
 2     1 Amazon before other                                 
 3     1 Google after  another one test text_sth another text
 4     1 Google before another text other                    
 5     1 Yahoo  after  another one test text_sth another text
 6     1 Yahoo  before another text other                    
 7     2 Amazon after  text here another text                
 8     2 Amazon before etc                                   
 9     2 Google after  text here                             
10     2 Google before test text_sth  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...