Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the '|' operator work in R?

Tags:

syntax

r

I'm trying to understand the | operator in R. Why does

a = 2
a == 3 | 4

return TRUE in R?

a == 3 

and

a == 4

each return FALSE so why does the second line return TRUE?

like image 399
goldisfine Avatar asked Dec 25 '22 07:12

goldisfine


2 Answers

See help(Syntax) -- the == has higher precedence than the |.

So:

R> a <- 2
R> a == 3 | 4
R> TRUE
R> a == (3 | 4)
R> FALSE
like image 134
Dirk Eddelbuettel Avatar answered Jan 14 '23 04:01

Dirk Eddelbuettel


Think of it like this:

`|`(a == 3, 4)
`==`(a, 3)
as.logical(2) # TRUE
as.logical(3) # TRUE
as.logical(4) # TRUE

So, what is happening is that both sides of a == 3 are coerced to logical; that evaluates to TRUE == TRUE which is TRUE. After that an or operation between TRUE and 4 returns TRUE.

like image 42
asb Avatar answered Jan 14 '23 05:01

asb