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

Time:07-05

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?

CodePudding user response:

dim(var) == c(1,1) gives two TRUE. See R News below. So we should use identical(dim(var), c(1L, 1L)) or all(dim(var) == c(1,1)) now.

This also drives me crazy. Previously we were told that && and || are safe to use in if (). But now, we need be more careful.

This change has affected a few R packages. Because the code that used to work smoothly suddenly throws warnings.

changes

  •  Tags:  
  • r
  • Related