vendredi 15 mai 2020

Nesting ifelse in R

I'm trying to nest ifelse in R to create a new vector C, where if both vectors A and B are missing, then NA; otherwise, if either vector contains 1, then "Yes"; otherwise, "No". Example:

A  B  C
1  1  Yes
1  0  Yes
0  1  Yes
0  0  No
NA 1  Yes
0  NA No
NA NA NA

The below is what I've been playing around with in various iterations, but I can't get it to work correctly. Any suggestions?

df <- df %>% mutate(C=ifelse((is.na(A) & is.na(B)), NULL, ifelse((A==1 | B==1), "Yes", "No")))

(Perhaps there's a better way which doesn't use ifelse at all, which I'd also be open to, but for my own understanding it would be nice to know how to get this way to work as well!)

Many thanks!

Aucun commentaire:

Enregistrer un commentaire