Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract all dataframes from a list which contains certain columns

I have a list like:

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
Hight <- c(13, 41, 32, 58, 26)
Weight <- c(11,43,23,43,123)

df1 <- data.frame(Name, Age, Hight, Weight)
df2 <- data.frame(Name, Age, Hight)
df3<- data.frame(Name, Age, Weight)

l <- list(df1, df2, df3)

I want now to extract all dataframes (or the name of the dataframes), which contain the Hight andWeight columns.

The expected output in this case would list(df1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use this

l <- list(df1, df2, df3)

l[sapply(l , \(x) all(c('Weight', 'Hight') %in% colnames(x)))]
  • output
[[1]]
   Name Age Hight Weight
1   Jon  23    13     11
2  Bill  41    41     43
3 Maria  32    32     23
4   Ben  58    58     43
5  Tina  26    26    123
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading