Reputation: 7730
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)
Upvotes: 27
Views: 57333
Reputation: 4352
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')}
Upvotes: 29
Reputation: 52428
Simply use length()
like so:
foo <- logical(0)
if(length(foo) == 0) { } # TRUE
if(length(foo) != 0) { } # FALSE
Upvotes: 5
Reputation: 4930
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
Upvotes: 8
Reputation: 7164
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
Upvotes: 7