“missing value where TRUE/FALSE needed” Error in if statement in R [duplicate]

萝らか妹 提交于 2019-12-20 07:09:34

问题


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.

Could you help me please? How can I write my condition in if statement without getting this error?

My Code:

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)  
}

回答1:


when DATA[i,2] is NA, the comparison is also NA:

NA != NA
#[1] NA

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]))


来源:https://stackoverflow.com/questions/28474630/missing-value-where-true-false-needed-error-in-if-statement-in-r

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