[Rd] ROBUSTNESS: x || y and x && y to give warning/error if length(x) != 1 or length(y) != 1
henrik@bengt@@on @ending from gm@il@com
Wed Aug 29 05:03:21 CEST 2018
'x || y' performs 'x || y' for length(x) > 1. For instance (here
using R 3.5.1),
> c(TRUE, TRUE) || FALSE
> c(TRUE, FALSE) || FALSE
> c(TRUE, NA) || FALSE
> c(FALSE, TRUE) || FALSE
This property is symmetric in LHS and RHS (i.e. 'y || x' behaves the
same) and it also applies to 'x && y'.
Note also how the above truncation of 'x' is completely silent -
there's neither an error nor a warning being produced.
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
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)
> logical(0) || logical(0)
> logical(0) && logical(0)
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
PS. This is in the same vein as
- in R (>=3.4.0) we now get that if (1:2 == 1) ... is an error if
More information about the R-devel