EN VI

keep data.frame from list based on condition?

2024-03-11 23:00:05
How to 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:

> 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
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login