【问题标题】:Error in if/while (condition) {: missing Value where TRUE/FALSE neededif/while(条件)出错{:缺少需要 TRUE/FALSE 的值
【发布时间】:2017-10-01 01:26:16
【问题描述】:

我收到此错误消息:

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

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

这是什么意思,我该如何预防?

【问题讨论】:

  • 双等号运算符不能容忍任一侧的NA。如果我定义:x = NA,然后执行if (x == NA){ ... },那么当解析器检查双等号的左侧时,将在运行时抛出此错误。要纠正此错误,请使用 is.na(your_variable) 确保条件中的每个变量都不是 NA。
  • 太棒了,这解决了我在闪亮的 daterangeinputs 上使用 observe() 函数时遇到的问题。

标签: r r-faq


【解决方案1】:

condition 的评估产生了NAif 条件必须有 TRUEFALSE 结果。

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

要测试是否缺少对象,请使用is.na(x) 而不是x == NA


另见相关错误:

Error in if/while (condition) { : argument is of length zero

Error in if/while (condition) : argument is not interpretable as logical

if (NULL) {}
## Error in if (NULL) { : argument is of length zero

if ("not logical") {}
## Error: argument is not interpretable as logical

if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used

【讨论】:

    【解决方案2】:

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

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

    改成

    if (is.null(x) || x == '') {
    

    【讨论】:

    • 仅供参考,还有!(length(x) == 1L && nzchar(x))
    【解决方案3】:

    这适用于"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])
      }
    

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 2013-12-10
      • 2019-02-25
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多