dasf
dasf

Reputation: 1045

R: boolean OR and double equal

Say a=1; b=2. Why does (a|b)==1 yield TRUE but (a|b)==2 FALSE? What then is a simple way to return TRUE if either (or both) variable is a match?

Upvotes: 1

Views: 584

Answers (2)

alistaire
alistaire

Reputation: 43344

| compares two Boolean values.

In this case, (a|b) itself returns TRUE because the numbers are coerced to Boolean values by turning 0 into FALSE, and everything else into TRUE.

From ?base::Logic:

Numeric and complex vectors will be coerced to logical values, with zero being false and all non-zero values being true. Raw vectors are handled without any coercion for !, &, | and xor, with these operators being applied bitwise (so ! is the 1s-complement).

== doesn't work that way, though; it coerces the TRUE into it's numeric form, 1, so 1==2 returns FALSE.

From ?base::Comparison:

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

Upvotes: 2

steveb
steveb

Reputation: 5532

If you look at the numeric values that TRUE and FALSE evaluate to, they are 1 and 0 respectively

as.numeric(c(TRUE, FALSE))
#[1] 1 0

Upvotes: 2

Related Questions