Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset list of dataframes containing specific column name

I have a list of dataframes and I'd like to get column x from each dataframe as a string.

testing <- list(data.frame(A = "Yes", B = "No"),
                data.frame(B = "No", C = "No"),
                data.frame(A = "Yes"))

I can print which of the dataframes have a colname A in them, but I haven't been able to make the connection to subsetting the original testing

lapply(testing, function(x) "A" %in% colnames(x))

Desired Output

[[1]]
    A  B
1 Yes No

[[2]]
    A
1 Yes
like image 909
MayaGans Avatar asked Dec 06 '22 08:12

MayaGans


1 Answers

Another base option is Filter

out <- Filter(function(x) "A" %in% names(x), testing)
out
#[[1]]
#    A  B
#1 Yes No
#
#[[2]]
#    A
#1 Yes
like image 131
markus Avatar answered Feb 23 '23 12:02

markus