【问题标题】:R - " missing value where TRUE/FALSE needed " [duplicate]R - “需要 TRUE/FALSE 的缺失值” [重复]
【发布时间】:2015-01-17 01:36:50
【问题描述】:

我正在尝试在 R 中执行以下代码

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

但我遇到了一个错误

Error in if (comments[l] != NA) print(comments[l]) : missing value where TRUE/FALSE needed

这里发生了什么?

【问题讨论】:

    标签: r if-statement syntax


    【解决方案1】:

    你能把if条件改成这样吗:

    if (!is.na(comments[l])) print(comments[l]);
    

    您只能使用 is.na() 检查 NA 值。

    【讨论】:

    • @user3582590:请考虑通过单击答案投票数下方的小复选标记来接受实际回答您问题的答案。这确定了对未来读者最有帮助的答案。
    【解决方案2】:

    检查命令:NA!=NA:你会得到结果NA,因此是错误消息。

    您必须使用函数 is.na 才能使您的 ifstatement 起作用(通常,最好使用此函数检查 NA 值):

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

    【讨论】:

    • ...用 is.na() 检查 NA,在我的情况下,接受它不是 NULL 并且 NA 和 NULL 都存在的残酷现实。
    • @Chris 有一个 is.null 函数虽然 ;-)
    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2015-06-28
    • 1970-01-01
    • 2019-03-07
    • 2013-12-10
    • 2018-07-12
    相关资源
    最近更新 更多