Question
Filter list of lists with purrr::keep
I have a reprex as follows:
library(dplyr)
library(purrr)
df1 <- data.frame(
col1 = 1:5,
col2 = 6:10
)
df2 <- df1 %>%
mutate(col3 = 1:5)
ls <- list(
a = list(df1 = df1),
b = list(
df1 = df1,
df2 = df2
),
c = list(
df2 = df2
)
)
I want to filter ls
so that elements of ls
that contain col3
by name are kept.
I have tried using keep but I am unable to index correctly at the right depth.
Expected solution:
list(
b = list(
df2 = df2
)
,c = list(
df2 = df2
)
)
This is close:
ls %>%
map(
~keep(.x, ~ "col3" %in% names(.x))
)