logical(0) in if statement
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')}
First off, logical(0)
indicates that you have a vector that's supposed to contain boolean values, but the vector has zero length.
In your first approach, you do
!is.na(c(NA, NA, NA))
# FALSE, FALSE, FALSE
Using the which()
on this vector, will produce an empty integer vector (integer(0)
). Testing whether an empty set is equal to zero, will thus lead to an empty boolean vector.
In your second approach, you try to see whether the vector which(!is.na(c(NA,NA,NA))) == 0
is TRUE
or FALSE
. However, it is neither, because it is empty. The if
-statement needs either a TRUE
or a FALSE
. That's why it gives you an error argument is of length zero
Calling which
to check whether a vector of logicals is all false is a bad idea. which
gives you a vector of indices for TRUE values. If there are none, that vector is length-0. A better idea is to make use of any
.
> any(!is.na(c(NA,NA,NA)))
FALSE