Susu
Susu

Reputation: 61

Using logical 'or' operator correctly with multiple conditions?

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...

Upvotes: 0

Views: 55

Answers (2)

tobiasegli_te
tobiasegli_te

Reputation: 1463

Try

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

or

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

However the second solution is clearly less elegant, I just added it to show you how to use the logical OR. I would highly recommend to put logical arguments in parentheses.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234665

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.

Upvotes: 1

Related Questions