I have a list object below. I would like to remove df2 and df3 from the list since they do not have an "ID" column. how to get around this? many thanks in advance.
my_list <- list(df1 = data.frame(ID = 1:5, Name = letters[1:5]),
df2 = matrix(c(1, 2, 3, 4), ncol = 2),
df3 = data.frame(Name = letters[6:10], Age = c(20, 25, 30, 35, 40)))
sapply(my_list, function(x) "ID" %in% colnames(x))
for (i in sequence(my_list)) {
if (sapply(my_list, function(x) "ID" %in% colnames(x)) == FALSE) {
DROP THE df2 and df3
}
}
Filter() from base extracts the elements of a list for which a logical function gives true.
Filter(\(df) "ID" %in% colnames(df), my_list)
Equivalent options with purrr are keep/discard:
purrr::keep(my_list, ~ "ID" %in% colnames(.x))
purrr::discard(my_list, ~ !"ID" %in% colnames(.x))
$df1
ID Name
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
Using a for loop
for(nm in names(my_list)) if(!"ID" %in% names(my_list[[nm]])) my_list[[nm]] <- NULL
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