I know the part that && and || make for more efficient code because they do the least number of tests in a chain and break out as soon as we have enough information to know what the result of the chain is going to be.
- As soon as && hits a FALSE in a chain it stops evaluating and returns FALSE for the whole chain.
- As soon as || hits a TRUE in a chain it stops evaluating and returns TRUE for the chain
But I read in Garrett Grolemund's book that "...double operators are not appropriate everywhere. && and || are not vectorized, which means they can only handle a single logical test on each side of the operator..." Can somebody please explain to me what the emphasized part means?
Did some simple tests and while & is doing a element-wise comparison between the corresponding elements of the two logical vectors, && is comparing only the first elements and returning TRUE because the operator is not vecorized? Is that all the emphasized part above means, or is there more to it?
c(T, F, F, F, F) & c(T, T, F, T, F)
[1] TRUE FALSE FALSE FALSE FALSE
c(T, F, F, F, F) && c(T, T, F, T, F)
[1] TRUE
c(F, F, F, F, F) && c(T, T, F, T, F)
[1] FALSE
Collapsing vectors on either side of the operator to one boolean value using any
and all
.
any(T, T, F, F, T) && all(F, F, T, T, T)
[1] FALSE
any(T, T, F, F, T) && any(F, F, T, T, T)
[1] TRUE