Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter elements of a list column

Tags:

list

r

filter

purrr

I have a data frame (df) with 3 variables:

  • ID (1st id variable)
  • ID2 (2nd id variable)
  • 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:

  • ID2
  • DATE

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!

like image 274
Norbert Köhler Avatar asked Jan 27 '26 10:01

Norbert Köhler


1 Answers

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
like image 182
acylam Avatar answered Jan 28 '26 23:01

acylam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!