Search code examples
rdplyrtidyrdata-manipulationtidy

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
  }
} 

Solution

  • Using a for loop

    for(nm in names(my_list)) if(!"ID" %in% names(my_list[[nm]])) my_list[[nm]] <- NULL