Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using & in R (e.g 3 < (5 & 9) )

I am trying to learn R and understand how the & symbol works. I understand it to mean 'and'.

When I try 3 < (5 & 4) I get FALSE? I was expecting TRUE. Am I using & the wrong way?

like image 581
user3754366 Avatar asked Dec 08 '22 02:12

user3754366


2 Answers

In R TRUE evaluates to the number 1 in your arithmetic expression, hence:

3 < (5 & 4)
3 < TRUE
3 < 1

which is FALSE

You can convince yourself that R treats TRUE as 1 with the following code snippet:

> x <- c(-3:3)
> x
[1] -3 -2 -1  0  1  2  3
> x == TRUE
[1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
like image 168
Tim Biegeleisen Avatar answered Jan 05 '23 21:01

Tim Biegeleisen


I think what you meant by your statement was how we would say it in English "Is 3 less then 5 and 4?". But that is not what 3 < (5 & 4) means. As explained in other answers, R tries to figure out what (5 & 4) means first, then tries to figure out what it means for 3 to be less than TRUE. I think what you wanted is something like:

(3 < 4) & (3 < 5)

Another way to say it would be:

all(3 < c(4,5))
like image 25
nograpes Avatar answered Jan 05 '23 21:01

nograpes