R Warning 'length(x) = 2 > 1' in coercion to 'logical(1)'

Viewed 1736

Using R 4.1.3 I observe:

var <- 0
> if(is.data.frame(var) || is.vector(var)) var <- as.matrix(var)
> is.null(var) || (!is.matrix(var) && var == 0) || (dim(var)==c(1,1) && var[1,1]==0)
[1] TRUE

However, with R 4.2.1 I observe the warning on this same code

> var <- 0
> if(is.data.frame(var) || is.vector(var)) var <- as.matrix(var)
> is.null(var) || (!is.matrix(var) && var == 0) || (dim(var)==c(1,1) && var[1,1]==0)
[1] TRUE
Warning message:
In dim(var) == c(1, 1) && var[1, 1] == 0 :
  'length(x) = 2 > 1' in coercion to 'logical(1)'

Having a hard time finding the root cause here. Any thoughts on a reason this occurs now and a good fix?

1 Answers

dim(var) == c(1,1) gives two TRUE. See R News below. Possible replacements are

identical(dim(var), c(1L, 1L))
all(dim(var) == c(1,1))

Previously we were told that && and || are safe to use in if () as they silently return a single TRUE or FALSE. But now it will warn you. This actually makes it easier to detect bugs, so I am happy with this change.

Unfortunately, this change has affected a few R packages (see for example: Package ceases to work due to "if" error: condition has length > 1). As a result, the code that used to work smoothly suddenly throws warnings or even errors.

change

Related