【问题标题】:R: Select data across multiple columns and conditionsR:跨多个列和条件选择数据
【发布时间】:2016-11-07 19:46:19
【问题描述】:

我有一个名为 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 范围内的观察值,包括 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 中满足范围而不维护数据帧结构的数字列表。如何将范围条件应用于数据框中的多个列?

【问题讨论】:

  • 这里有一个使用rowSums的方法:test[rowSums(test > 649 & test < 661) > 0,]
  • 这是另一个(不必要地过于复杂)可能的解决方案library(data.table) ; setDT(test)[, .SD[Reduce(`|`, lapply(.SD, between, 650, 660))]]
  • 基地R的另一种方式:test[apply(test,1,function(x) any(x>=650 &x<=660)),]
  • @lmo 如果您不忙于寻找欺骗行为,您可以发布该内容。另一种选择是as.logical 而不是> 0
  • 谢谢@Frank。如果不是彻头彻尾的欺骗,也存在类似的问题,但我目前找不到一个很好的例子。

标签: r dataframe subset


【解决方案1】:

简而言之:

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

【讨论】:

    【解决方案2】:

    一种方法是:

    # 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), ]
    

    【讨论】:

    • 这里没关系,但是OP声称有一个data.frame,而你的构造是一个矩阵。
    • 这将导致我正在寻找的内容,但我要输入的列不止三列。您的解决方案是否有可能被推广?
    【解决方案3】:

    您可以使用applyany 查找感兴趣的行,然后对原始行进行子集化。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2021-09-01
      • 2018-07-23
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多