I'm wondering how can I subset dataframes by their column names from a list of dataframe?
For example I have MyDfList, a list of 3 dataframes with 4 columns, and I just want to keep only two columns (A and D) from all the dataframe in the list.
MyDfList <- list(data.frame(A = "S1", B = "2208", C ="2399", D="1.086504"),
data.frame(A = "S2", B = "6756", C ="6970", D="1.031676"),
data.frame(A = "S3", B = "8271", C ="8401", D="1.015718"))
I was trying but couldn't get through.
out0<-lapply(MyDfList , function(x) c("A","D") %in% colnames(x))
out1 <- Filter(function(x) c("A","D") %in% names(x), MyDfList )
out2<-MyDfList[sapply(MyDfList , function(x) c("A","D") %in% colnames(x))]
base R:
Here we subset each dataframe by passing the anonymous function
df[, c("A", "D")]to each data frame with lapply().tidyverse:
Here we pass the anonymous function
~select(., A, D)withmapto each dataframe.