I am new to R and I am trying to understand why when we use && or || between two logical vectors it returns just 1 element
a<-c(TRUE,FALSE,TRUE)
b<-c(FALSE,FALSE,FALSE)
a&&b
Why doesn’t this return a logical vector?
I am new to R and I am trying to understand why when we use && or || between two logical vectors it returns just 1 element
a<-c(TRUE,FALSE,TRUE)
b<-c(FALSE,FALSE,FALSE)
a&&b
Why doesn’t this return a logical vector?
There are two kinds of logical operators in R, vectorized and not vectorized. The && and || are not vectorized. They are intended to be used with single TRUE or FALSE values on either side, and short-circuit evaluation is used: so if the result is known after evaluating the left-hand side, the right-hand side will not be evaluated. For example,
FALSE && fn()
is FALSE regardless of the value of fn(), so it won't be evaluated. This is useful in tests where the right-hand side might give an error, e.g.
if (is.numeric(x) && x + 1 > 0)
since x + 1 > 0 will give an error if x is not numeric.
The & and | operators are the vectorized versions. They take vectors of logicals on both sides, and return a vector of logical values. They will always evaluate both sides. They need to do this in examples like
FALSE & fn()
because even though the result is known to be false, the length may change depending on the result of calling fn().
In upcoming versions of R, it will be an error to use something like your example, because it doesn't make sense to use && with length 3 vectors.