我有一个名为test的dataframe,如下所示:
> 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中满足范围的数字列表,而不需要维护dataframe结构。如何将范围条件应用于数据帧中的多列?
发布于 2016-11-07 19:56:53
简明扼要:
test <- test[apply(test, 1, function(x) any(x >= 650 & x <= 660)), ]发布于 2016-11-07 19:53:09
这样做的一种方法是:
# 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), ]发布于 2016-11-07 19:56:42
您可以使用apply和any查找感兴趣的行,然后对原始行进行子集。
goodvals <- apply(test <= 660 & test >= 650, 1, any)
test[goodvals, ]https://stackoverflow.com/questions/40473341
复制相似问题