Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove data frame from list if doesn’t satisfy a condition

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
  }
} 
like image 890
Seyma Kalay Avatar asked Mar 13 '26 14:03

Seyma Kalay


2 Answers

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))
Output
$df1
  ID Name
1  1    a
2  2    b
3  3    c
4  4    d
5  5    e
like image 184
Darren Tsai Avatar answered Mar 15 '26 04:03

Darren Tsai


Using a for loop

for(nm in names(my_list)) if(!"ID" %in% names(my_list[[nm]])) my_list[[nm]] <- NULL
like image 40
akrun Avatar answered Mar 15 '26 03:03

akrun