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

keep data.frame from list based on condition?

d1 <- data.frame(y1=c(1,2,3), y2=c(4,5,6), y3=c(8,8,8), y4=c(1,1,1))
d2 <- data.frame(y1=c(3,2,1), y2=c(6,5,4), y3=c(4,4,4), y4=c(10,10,10))
d3 <- data.frame(y1=c(6,5,4), y2=c(3,2,1), y3=c(8,8,8), y4=c(1,1,1))
d4 <- data.frame(y1=c(9,9,9), y2=c(8,8,8), y3=c(8,8,8), y4=c(1,1,1))

dat = mget(paste0("d", 1:4))  

From this list I want to keep the dataframe(s) where (1) y3 is between 1 and (2) 5 and y4 is between 5 and 11.

Values in y3 and y4 are the same in each dataframe.

The final output will be:

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

> dat
   $d2
     y1 y2 
   1  3  6  
   2  2  5  
   3  1  4 

>Solution :

Filter (note the capital F) is a base function that can filter a list based on a function. Here we write a custom anonymous function based on your criteria. I wasn’t really sure whether your "between" means > or >=, but you can edit easily as you like.

Filter(x = dat, f = \(x) all(x$y3 > 1 & x$y3 < 5 & x$y4 > 5 & x$y4 < 11))
# # $d2
# #   y1 y2 y3 y4
# # 1  3  6  4 10
# # 2  2  5  4 10
# # 3  1  4  4 10
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