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))
)
keep
I couldn't get it to work correctly. I have marked yours as the preferred answer simply for readability and conciseness. – Kloof