"!(2>3) + 2
[1] FALSE
!(2>3) + 0:5
[1] TRUE FALSE FALSE FALSE FALSE FALSE
z <- (1 > 2)
is.logical(z)
[1] TRUE"
Consulta realizada correctamente
These examples demonstrate how R handles "conflicts" between different types of operations and how it manages collections of data (vectors).
1. !(2>3) + 2 → FALSE
This is another result of Operator Precedence. In R, the addition operator (+) is much stronger than the negation operator (!).
What you expect: NOT (2 > 3) is NOT FALSE, which is TRUE. Then TRUE + 2 should be 3.
What R does: It groups the + 2 with the expression immediately to its left.
First, it evaluates the comparison: (2 > 3) is FALSE.
Now the expression is !FALSE + 2.
Because + happens before !, R calculates FALSE + 2 first.
FALSE is coerced to 0. So, 0 + 2 = 2.
Finally, it applies the negation: !2.
In R, any non-zero number is treated as TRUE for logical operations. Therefore, NOT 2 (NOT TRUE) becomes FALSE.
- !(2>3) + 0:5 → TRUE FALSE FALSE FALSE FALSE FALSE
This uses the same precedence rule but adds Vectorization into the mix.
Step-by-Step:
2 > 3 is FALSE.
0:5 creates a vector: c(0, 1, 2, 3, 4, 5).
R evaluates the addition first: FALSE + c(0, 1, 2, 3, 4, 5).
FALSE becomes 0, and is added to every number in the vector (Recycling). Result: c(0, 1, 2, 3, 4, 5).
Now R applies ! to that entire vector: !c(0, 1, 2, 3, 4, 5).
The Result:
!0 is TRUE (because 0 is the only "False" number).
!1, !2, !3, etc., are all FALSE (because non-zero numbers are "True").
- z <- (1 > 2) and is.logical(z) → TRUE
This is the simplest case because of the Parentheses.
The parentheses force R to finish the comparison (1 > 2) before doing anything else.
1 > 2 is strictly a logical comparison, so the result stored in z is the logical value FALSE.
Since z is a "logical" data type, is.logical(z) correctly returns TRUE.
The Golden Rule for R Logic
If you are combining a logical test (!, >, ==) with an arithmetic operation (+, *, /), always wrap your logical test in parentheses.
Bad: !x + y (Does !(x+y))
Good: (!x) + y (Does (Not x) + y)