Idea
In the spirit of Issue #38 (if/while (c(TRUE, TRUE)) ...) of giving a warning (soon error), @hadley proposed in a Tweet:
@HenrikBengtsson as part of new if() warning, I wonder if && and || should give warning when collapsing vector to scalar
Issue
Today we have that x || y performs x[1] || y for length(x) > 1. For instance,
> c(TRUE, TRUE) || FALSE
[1] TRUE
> c(TRUE, FALSE) || FALSE
[1] TRUE
> c(TRUE, NA) || FALSE
[1] TRUE
> c(FALSE, TRUE) || FALSE
[1] FALSE
This property is symmetric in LHS and RHS (i.e. y || x behaves the same) and it also applies to x && y.
The issue is that the above truncation of x is completely silent -there's neither an error nor a warning being produced.
Discussion/Suggestion
Using x || y and x && y with a non-scalar x or y is likely a mistake. Either the code is written assuming x and y are scalars, or there is a coding error and vectorized versions x | y and x & y were intended. Should x || y always be considered an mistake if length(x) != 1 or length(y) != 1? If so, should it be a warning or an error? For instance,
> x <- c(TRUE, TRUE)
> y <- FALSE
> x || y
Error in x || y : applying scalar operator || to non-scalar elements
Execution halted
What about the case where length(x) == 0 or length(y) == 0? Today x || y returns NA in such cases, e.g.
> logical(0) || c(FALSE, NA)
[1] NA
> logical(0) || logical(0)
[1] NA
> logical(0) && logical(0)
[1] NA
I don't know the background for this behavior, but I'm sure there is an argument behind that one. Maybe it's simply that || and && should always return a scalar logical and neither TRUE nor FALSE can be returned.
Idea
In the spirit of Issue #38 (
if/while (c(TRUE, TRUE)) ...) of giving a warning (soon error), @hadley proposed in a Tweet:Issue
Today we have that
x || yperformsx[1] || yforlength(x) > 1. For instance,This property is symmetric in LHS and RHS (i.e.
y || xbehaves the same) and it also applies tox && y.The issue is that the above truncation of
xis completely silent -there's neither an error nor a warning being produced.Discussion/Suggestion
Using
x || yandx && ywith a non-scalarxoryis likely a mistake. Either the code is written assumingxandyare scalars, or there is a coding error and vectorized versionsx | yandx & ywere intended. Shouldx || yalways be considered an mistake iflength(x) != 1orlength(y) != 1? If so, should it be a warning or an error? For instance,What about the case where
length(x) == 0orlength(y) == 0? Todayx || yreturnsNAin such cases, e.g.I don't know the background for this behavior, but I'm sure there is an argument behind that one. Maybe it's simply that
||and&&should always return a scalar logical and neitherTRUEnorFALSEcan be returned.