【问题标题】:Using OR logical operator when comparing two columns in R比较 R 中的两列时使用 OR 逻辑运算符
【发布时间】:2019-03-29 02:38:31
【问题描述】:

我有一个大型数据框,我在其中打印与另一列不匹配的列。我能够将第 4 列和第 9 列与这段代码的 sn-p 进行比较:

test_no_match <- newtest[which(newtest[,4] != newtest[,9] ),]

但是,我想打印一个数据框,其中第 4 列和第 9 列不匹配,或者如果第 6 列和第 11 列不匹配。因此,如果任一参数为真,它将打印。

我尝试过使用:

testnomatch <- (newtest[which(newtest[, 4] != newtest[, 9] ), ] || newtest[which(newtest[, 6] != newtest[, 11] ), ])

但我不断收到类似

的错误

“x”中的“x”类型无效 ||是的

有没有办法同时比较多个参数?谢谢你。

【问题讨论】:

  • test_no_match
  • 您可以使用Reduce 一次测试多个参数。请提供具有所需结果的可重现示例,以便我们进一步帮助您。
  • 当我尝试添加括号分隔时,我得到“|”只为相同大小的数据框定义

标签: r syntax logic logical-operators


【解决方案1】:

怎么了……

 testnomatch<- (newtest[which(newtest[,4] != newtest[,9] ),] || newtest[which(newtest[,6] != newtest[,11] ),]) 

几件事。

首先,|| 需要一个长度为 1 的条件,并且旨在用于像if(a || b) .... 这样的条件语句。

其次,| 是用来连接两个相同长度条件。在这里你有一些不同的东西。

所以把这些碎片放在一起:

 condition1 <- newtest[,4] != newtest[,9]
 condition2 <- newtest[,6] != newtest[,11]
 jointcondition <- condition1 | condition2
 testnomatch <- newtest[which(jointcondition),]

或者在一行中:

 newtest[which((newtest[,4] != newtest[,9]) | (newtest[,6] != newtest[,11])),]

这应该可行,但当然,我没有机会尝试,因为您没有提供可重现的示例 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多