“missing value where TRUE/FALSE needed” Error in i

2020-05-09 00:28发布

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条回答
乱世女痞
2楼-- · 2020-05-09 00:52

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]))
查看更多
登录 后发表回答