0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Personally I believe the second way only becomes less elegant with all the superfluous parentheses, but upvoted nonetheless.
Thanks to both of you! @Bathsheba greatly helped me to understand where it went wrong while you offer a different solution! Thanks, again!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.