svenkatesh svenkatesh - 1 month ago 12
R Question

R: Select data across multiple columns and conditions

I have a dataframe called

test
that looks like this:

> test
dx1 dx2 dx3
1 659 658 657
2 653 651 690
3 249 786 654
4 647 655 656
5 900 654 658
6 800 224 104


I want to keep only the observations that have at least one column that falls in the range 650 - 660, inclusive. In this case, the result should look like:

dx1 dx2 dx3
1 659 658 657
2 653 651 690
3 249 786 654
4 647 655 656
5 900 654 658


So far, I've tried using
test[test %in% c(650 : 660)]
, but this returns a list of numbers in
test
that satisfy the range without maintaining the dataframe structure. How can I apply the range condition to multiple columns in a dataframe?

Answer

Succinctly:

test <- test[apply(test, 1, function(x) any(x >= 650 & x <= 660)), ]