mardi 2 mars 2021

Error in if statement with NA in data in R

I have a problem with a in if statement. I get an error message saying "absent value where TRUE / FALSE is required". I am trying to calculate a new variable using an if statement and a for cycle, but the data has NA values and the cycle I used cannot work any further after finding a NA value.

This is the variables I am using to create the new variable:

x=c(3,3,3,2,NA,2,3,NA,3,NA)
y=c(3,6,5,4,NA,3,2,NA,3,NA)
h=c(1,2,1.6666667,2,NA,1.5,0.6666667,NA,1,NA)

This the code I am using that has the problem with NA value:

z=rep(NA,length(y))
for(i in 1:length(x)){
if((x[i]==0 & y[i]>=3) | h[i]>=3){
  z[i]=1
} else if((x==0 & y[i]<3) | h[i]<3){
  z[i]=0
}
}

Can you tell me how could I include the NA values into the if statement or what should I do? Thanks for your reply.

Aucun commentaire:

Enregistrer un commentaire