Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

r - Why does as.numeric(1) == (3 | 4) evaluate to TRUE?

I wanted to make a simple comparison using h == 1 | 2 where h could be an integer between 1 and 4. To my astonishment, it didn't work.

I could sort of understand why

1 == 2 | 4

TRUE

and perhaps even why

1 == (2 | 4)

TRUE

but why in the name of all that's reasonable and sane does

as.numeric(1) == (2 | 4)

or

1L == (2 | 4)

or

3 == 2 | 4

evaluate to

TRUE

???

How can I ask R to tell me whether 1 is equal to 2 or 4 and the answer will be FALSE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
1 == 2 | 4

Operator precedence tells us it is equivalent to (1 == 2) | 4

1 == 2 is FALSE, 4 is coerced to logical (because |is a logical operator), as.logical(4) is TRUE, so you have FALSE | TRUE, that's TRUE

Indeed coercion rules for logical operators (?Logic) tell us that:

Numeric and complex vectors will be coerced to logical values, with zero being false and all non-zero values being true.


3 == 2 | 4

Same thing


1 == (2 | 4)

2 | 4 will be coerced to TRUE | TRUE, which is TRUE. Then 1 == TRUE is coerced to 1 == 1 which is TRUE.

Indeed coercion rules for comparison operators (?Comparison) tell us that:

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.


as.numeric(1) == (2 | 4)

Same thing


1L == (2 | 4)

Same again


1 is equal to 2 or 4

is actually (1 is equal to 2) or (1 is equal to 4), which is:

(1==2)|(1==4)

which is

FALSE | FALSE

which is FALSE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...