mardi 16 avril 2019

if else with missing observations in R

Lets say I have following 2 variables

z1=c(0,1,1,0,NA,1,0,NA ,1)
z2=c(0,1,0,NA,1,0,0,0,NA)

So the both variables has missing values. I need to create a new variable Z as follows,

Z=1 if at least one of the variables are equal to 1.

Z=0 if at least one of the variables are equal to 0.

So i performed the following nested ifelse statement and got this output,

     ifelse(z1==1|z2==1,1,ifelse((z1==0|z2==0),0 ,0))
  0  1  1 NA  1  1  0 NA  1

there seems to be something wrong with my if-else statement as my ideal output should be something like this,

0  1  1 0  1  1  0 0  1

can any one help me to figure out what is incorrect in my code ?

Thank you

Aucun commentaire:

Enregistrer un commentaire