问题
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