I have a data frame (df) with 3 variables:
data (list column created with the tidyr::nest() function.
library(tidyverse)
library(lubridate)
dates <- ymd(c('2018-02-01', '2018-02-06', '2018-02-10',
'2018-02-21', '2018-04-05'))
df.1 <- tibble(ID = paste0('ID_', rep(1, 5)),
ID2 = LETTERS[1:5],
DATE = dates) %>%
group_by(ID) %>%
nest()
df.2 <- tibble(ID = paste0('ID_', rep(1, 6)),
ID2 = LETTERS[1:6])
df <- df.1 %>%
left_join(df.2, by = 'ID')
The list column (data) contains 2 variables:
I would like to keep all elements in the list column (data[[DATE]]) for which data[[ID2]] != df$ID2.
Is there any way to apply a filter function -- maybe of the purrr package?
Thanks very much in advance!
We can use map2. We feed the list-column (data) as .x argument and df$ID2 as .y argument and filter on each .x where .x$ID2 != .y:
library(tidyverse)
output <- df %>%
mutate(data = data %>% map2(ID2, ~ filter(.x, ID2 != .y)))
Output:
> output
# A tibble: 6 x 3
ID data ID2
<chr> <list> <chr>
1 ID_1 <tibble [4 x 2]> A
2 ID_1 <tibble [4 x 2]> B
3 ID_1 <tibble [4 x 2]> C
4 ID_1 <tibble [4 x 2]> D
5 ID_1 <tibble [4 x 2]> E
6 ID_1 <tibble [5 x 2]> F
> output %>%
+ pull(data)
[[1]]
# A tibble: 4 x 2
ID2 DATE
<chr> <date>
1 B 2018-02-06
2 C 2018-02-10
3 D 2018-02-21
4 E 2018-04-05
[[2]]
# A tibble: 4 x 2
ID2 DATE
<chr> <date>
1 A 2018-02-01
2 C 2018-02-10
3 D 2018-02-21
4 E 2018-04-05
[[3]]
# A tibble: 4 x 2
ID2 DATE
<chr> <date>
1 A 2018-02-01
2 B 2018-02-06
3 D 2018-02-21
4 E 2018-04-05
[[4]]
# A tibble: 4 x 2
ID2 DATE
<chr> <date>
1 A 2018-02-01
2 B 2018-02-06
3 C 2018-02-10
4 E 2018-04-05
[[5]]
# A tibble: 4 x 2
ID2 DATE
<chr> <date>
1 A 2018-02-01
2 B 2018-02-06
3 C 2018-02-10
4 D 2018-02-21
[[6]]
# A tibble: 5 x 2
ID2 DATE
<chr> <date>
1 A 2018-02-01
2 B 2018-02-06
3 C 2018-02-10
4 D 2018-02-21
5 E 2018-04-05
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With