Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 970
dhc Avatar asked Dec 28 '25 06:12

dhc


2 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

like image 94
Zheyuan Li Avatar answered Dec 30 '25 18:12

Zheyuan Li


I just ran in the same issue. I fixed my problem using a simple & rather than a double.

From this

filter(data, n > 1 && !!sym(group) %in% category_to_merge)

to this

filter(data, n > 1 & !!sym(group) %in% category_to_merge)
like image 39
Lucas Duval Avatar answered Dec 30 '25 18:12

Lucas Duval



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!