11

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
  • Try print(dim(var)). When var is a matrix, dim(var) will have length 2.
    – Limey
    Jul 3, 2022 at 17:13

1 Answer 1

23

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.