timothy.s.lau
timothy.s.lau

Reputation: 1101

multiple relational (comparison) operators: why isn't `x < y > z` a valid syntax?

This might be a dumb question, but I'm interested in why R doesn't allow multiple relational operators in a statement, say,

2 < 5 > 3

R returns

Error: unexpected '>' in "2 < 5 >"

instead of TRUE.

Upvotes: 1

Views: 71

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73405

I'm interested in why R doesn't allow multiple relational operators in a statement.

Could you name an example programming / scientific language that allows 0 < 5 > 3?

Suppose this syntax is legitimate, then what is the default rule for it? Which of the following is correct?

(0 < 5) > 3  =>  TRUE > 3  =>  1 > 3  =>  FALSE
0 < (5 > 3)  =>  0 < TRUE  =>  0 < 1  =>  TRUE

I think you know that the legitimate syntax is (0 < 5) && (5 > 3).


Note that the original question title "multiple logical operators" is imprecise. ">" is a relational operator not a logical one. Using multiple logical operators in a statement is not a problem, say

FALSE && FALSE || TRUE
!FALSE || TRUE

However, be aware that (mixed) logical operations are not associative:

(FALSE && FALSE) || TRUE  =>  FALSE || TRUE  =>  TRUE
FALSE && (FALSE || TRUE)  =>  FALSE && TRUE  =>  FALSE

(!FALSE) || TRUE  =>  TRUE || TRUE  =>  TRUE
!(FALSE || TRUE)  ==>  !TRUE  => FALSE

Upvotes: 2

Related Questions