[英]R - Using data.table to efficiently test rolling conditions across multiple rows and columns
[英]R: Select data across multiple columns and conditions
我有一个名为test
的数据框,如下所示:
> 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
中满足范围而不保持数据帧结构的数字列表。 如何将范围条件应用于数据框中的多个列?
一种方法是:
# 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), ]
您可以使用apply
和any
来查找感兴趣的行,然后将原始子集化。
goodvals <- apply(test <= 660 & test >= 650, 1, any)
test[goodvals, ]
简洁:
test <- test[apply(test, 1, function(x) any(x >= 650 & x <= 660)), ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.