Using the operator or the logical operator correctly with several conditions?

advertisements

I can't really seems to wrap my head around about how I am using the | operator incorrectly. Because my code seems to work correctly without it, I assume I've not understood correctly what it does. But I wasn't able to find an explanation that helps me get to it.

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

here should the return be [1] 1 4, but for some reason I just get back all the row indicies...


You need to write df$x1 == 1 & (df$x2 == 4 | df$x2 == 6)

Currently your expression is evaluated as

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

due to operator precedence, which is always true.