使用逻辑'或'操作员有多种条件吗?

时间:2016-10-07 08:31:56

标签: r

我似乎无法理解我如何使用|操作员错误。因为我的代码似乎在没有它的情况下正常工作,我认为我没有正确理解它的作用。但是我无法找到帮助我达到目的的解释。

x1 <- c(1,2,3,1,2,3)
x2 <- c(4,5,6,6,5,4)
df <- data.frame(x1,x2)

#simple test: find out which rows have value 1 for x1 and value 4 for x2 at the same time
which(df$x1 == 1 & df$x2 == 4)
[1] 1

#problem: find out which rows have value 1 for x1 and either value 4 or 6 for x2
which(df$x1 == 1 & df$x2 == 4 | 6)
[1] 1 2 3 4 5 6

这里应该返回[1] 1 4,但由于某种原因,我只是回到所有行标记......

2 个答案:

答案 0 :(得分:2)

尝试

which((df$x1 == 1) & (df$x2 %in% c(4,6)))

which((df$x1 == 1) & ((df$x2 == 4)|(df$x2 == 6)))

然而,第二种解决方案显然不那么优雅,我只是添加它来向您展示如何使用逻辑OR。 我强烈建议在括号中加入逻辑参数。

答案 1 :(得分:1)

您需要撰写df$x1 == 1 & (df$x2 == 4 | df$x2 == 6)

目前,您的表达式评估为

(df$x1 == 1 & df$x2 == 4) | 6

由于运算符优先级,它始终为真。