if/while(条件){:缺少需要TRUE/FALSE的值时出错

if/while(条件){:缺少需要TRUE/FALSE的值时出错,r,r-faq,R,R Faq,我收到了以下错误消息: Error in if (condition) { : missing value where TRUE/FALSE needed 或 这是什么意思,我如何防止它?对条件的评估导致NA。如果条件必须有TRUE或FALSE结果 if (NA) {} ## Error in if (NA) { : missing value where TRUE/FALSE needed 这可能会意外发生,因为计算结果如下: if(TRUE && sqrt(-1)) {}

我收到了以下错误消息:

Error in if (condition) { : missing value where TRUE/FALSE needed


这是什么意思,我如何防止它?

条件的评估导致
NA
如果
条件必须有
TRUE
FALSE
结果

if (NA) {}
## Error in if (NA) { : missing value where TRUE/FALSE needed
这可能会意外发生,因为计算结果如下:

if(TRUE && sqrt(-1)) {}
## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed

要测试对象是否丢失,请使用而不是
x==NA


另请参见相关错误:


我在检查null或空字符串时遇到了这个问题

if (x == NULL || x == '') {
改成

if (is.null(x) || x == '') {
这适用于
“NA”
而不适用于
NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

double equals运算符不能容忍两边的
NA
。如果我定义:
x=NA
,然后执行
If(x==NA){…}
然后,当解析器检查双等于的左侧时,将在运行时抛出此错误。要纠正此错误,请使用
is.NA(您的_变量)
确保条件中的每个变量都不是NA。令人惊讶的是,这解决了我在observe()中遇到的问题函数在shinny.Fyi中的daterangeinputs,还有
!(长度(x)=1L&&nzchar(x))
if (is.null(x) || x == '') {
comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }