logical(0) in if statement

user1700890 picture user1700890 · Feb 5, 2018 · Viewed 27.1k times · Source

This line:

which(!is.na(c(NA,NA,NA))) == 0

produces logical(0)

While this line

if(which(!is.na(c(NA,NA,NA))) == 0){print('TRUE')}

generates:

Error in if (which(!is.na(c(NA, NA, NA))) == 0) { : 
  argument is of length zero

Why there is an error? What is logical(0)

Answer

efbbrown picture efbbrown · Feb 5, 2018

logical(0) is a vector of base type logical with 0 length. You're getting this because your asking which elements of this vector equal 0:

> !is.na(c(NA, NA, NA))
[1] FALSE FALSE FALSE
> which(!is.na(c(NA, NA, NA))) == 0
logical(0)

In the next line, you're asking if that zero length vector logical(0) is equal to 0, which it isn't. You're getting an error because you can't compare a vector of 0 length with a scalar.

Instead you could check whether the length of that first vector is 0:

if(length(which(!is.na(c(NA,NA,NA)))) == 0){print('TRUE')}