logical(0) in if statement

我与影子孤独终老i 提交于 2020-01-02 03:15:53

问题


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)


回答1:


logical(0) is a vector of class 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')}



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/48626193/logical0-in-if-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!