Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical(0) in if statement

Tags:

r

if-statement

na

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)

like image 624
user1700890 Avatar asked Feb 05 '18 15:02

user1700890


People also ask

What is logical 0?

"Logic 0" and "logic 1" represent binary digits (0 and 1) or Boolean logic conditions (true and false). Thinking in terms of logic 0 and logic 1 allow engineers to design circuits and logic gates at a high level of abstraction that is removed from implementation considerations.

Is logical 0 True or false?

In Map Algebra, any non-zero input value is considered to be a logical true, and zero is considered a logical false. Some Map Algebra operators and functions evaluate input cell values and return logical 1 values (true) and logical 0 values (false). The relational and Boolean operators all return logical values.

What is logical zero in r?

First off, logical(0) indicates that you have a vector that's supposed to contain boolean values, but the vector has zero length.

What is the difference between logical 0 and null?

NULL is a "zero-length" object, so any elementwise comparison or operation with NULL will have length zero: logical(0) represents a logical vector of length zero. You might find identical() useful: identical(NULL,NULL) is TRUE, identical(NULL,NA) is FALSE.


1 Answers

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')}
like image 76
efbbrown Avatar answered Sep 24 '22 15:09

efbbrown