Skip to content

ROBUSTNESS: x || y and x && y to give warning/error if length(x) != 1 or length(y) != 1 #48

Description

@HenrikBengtsson

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions