“需要真/假所需的缺失值” R中的if语句错误 [英] "missing value where TRUE/FALSE needed" Error in if statement in R

查看:294
本文介绍了“需要真/假所需的缺失值” R中的if语句错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计数并打印我数据框的第二列和第三列中的值名为DATA的情况。
但是我有错误的值需要TRUE / FALSE错误。

I am trying to count and print the cases in which the values in second and third columns of my dataframe named 'DATA'. But I have "missing value where TRUE/FALSE needed" Error.

您能帮我吗?

我的代码:

deneme<-function(id=vector()){
i<-1
counter<-1
sulfate<-DATA[,2]
nitrate<-DATA[,3]
while (DATA[i,4] == DATA[i+1,4]){
if(DATA[i,2] != NA & DATA[i,3] != NA){
counter<-counter+1

}
i<-i+1
}

print(counter)  
}


推荐答案

DATA [i,2] NA 时,比较也是 NA

NA != NA
#[1] NA

您需要使用函数 is.na 来测试您是否拥有 NA value:

You need to use function is.na to test wether you have NA value:

!is.na(NA)
#[1] FALSE

因此,您应该将您的代码行更改为:

Hence, you should change your line of code to:

if(!is.na(DATA[i,2]) & !is.na(DATA[i,3]))

这篇关于“需要真/假所需的缺失值” R中的if语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆