R:选择多个列的条件

问题描述:

我有一个数据帧称为test看起来像这样的数据:R:选择多个列的条件

> 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 

我想只保留至少有一列,在范围650落在观察 - 660,包括在内。在这种情况下,结果应该是这样的:

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

到目前为止,我已经使用test[test %in% c(650 : 660)]尝试过,但这个数字返回在test满足范围不保持数据帧结构的列表。如何将范围条件应用于数据框中的多个列?要做到这一点

+5

下面是使用'rowSums'的方法:'测试[rowSums(测试> 649试验 0,]' – lmo

+2

这里的另一个(不必要地过度复杂)可能解决方案'''library(data.table); setDT(test)[,.SD [Reduce('|',lapply(.SD,between,650,660))]]''' –

+1

''' ':'test [apply(test,1,function(x)any(x> = 650&x Haboryme

为简洁:

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

一种方法是:

# set up your dataset 
dx1 <- c(659, 653, 249, 647, 900, 800) 
dx2 <- c(658, 651, 786, 655, 654, 224) 
dx3 <- c(657, 690, 654, 656, 658, 104) 
# bind the created vectors together 
test <- cbind(dx1, dx2, dx3) 

# filter based on your conditions  
test[(test[, 1] >= 650 & test[, 1] <= 660) | 
    (test[, 2] >= 650 & test[, 2] <= 660)| 
    (test[, 3] >= 650 & test[, 3] <= 660), ] 
+0

这里没关系,但OP声称有一个data.frame,而你的构造是一个矩阵。 – Frank

+0

这会导致我在找什么,但我有三个以上的列输出。你的解决方案有可能被普遍化吗? – svenkatesh

您可以使用applyany找到感兴趣的行,然后子集原件。

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