goldisfine
goldisfine

Reputation: 4850

How does the '|' operator work in 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?

Upvotes: 4

Views: 117

Answers (3)

asb
asb

Reputation: 4432

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.

Upvotes: 2

Señor O
Señor O

Reputation: 17432

a == 3 | 4 

Means:

Is either (a equal to 3) or (4)?

Coincidentally, 4 evaluates to TRUE when coerced to logical.

Upvotes: 1

Dirk is no longer here
Dirk is no longer here

Reputation: 368609

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

Upvotes: 7

Related Questions