I have a database like this
# col1 col2
#1 5 c('a','b','c')
#2 3 c('a','b','c','f')
#3 6 c('a','b','f')
#4 12 c('a','b','f')
#5 77 c('b','f')
#6 3 c('b','f','c')
and I want to filter all the rows which 'c' is %in%
col2 (rows 1,2,6 in the example).
I tried using filter(data, 'c' %in% col2)
but it didn't work.
CodePudding user response:
col2
looks like a list column. For list columns, you need to apply your condition to each element individually. You can accomplish this with purrr:map_lgl()
or base::sapply()
. Using purrr
:
library(dplyr)
library(purrr)
filter(data, map_lgl(col2, ~ 'c' %in% .x))
CodePudding user response:
library(tidyverse)
data <- tibble(
col1 = c(5, 3, 77),
col2 = c(list(letters[1:3]), list(letters[1:4]), list(c("b", "f")))
)
data
#> # A tibble: 3 × 2
#> col1 col2
#> <dbl> <list>
#> 1 5 <chr [3]>
#> 2 3 <chr [4]>
#> 3 77 <chr [2]>
data %>% filter(col2 %>% map_lgl(~ "c" %in% .x))
#> # A tibble: 2 × 2
#> col1 col2
#> <dbl> <list>
#> 1 5 <chr [3]>
#> 2 3 <chr [4]>
Created on 2022-03-11 by the reprex package (v2.0.0)