rlistlapply

Find column name in list of dataframes in R


I'd like to isolate the dataframes within a list of dataframes that include a certain column name. How would I search for the example elements that contain the column name b?

Ideally I'd like to use an elegant solution like map and purrr!

example <- list(data.frame(a = NA, b = NA),
                data.frame(a = NA, c = NA),
                data.frame(b = NA, d = NA))

Desired Output

1 3

Solution

  • You can do:

    which(sapply(example, function(x) any(names(x) == "b")))
    
    [1] 1 3
    

    One purrr option could be:

    which(map_lgl(example, ~ any(names(.) == "b")))