Can someone please help me understand how R handles NA in ifelse statements?
Let's say I have the following vectors:
x <- c(1, 1, 3, NA, 4)
y <- c(1, NA, 1, NA, NA)
I want to create another vector based on these two vectors, and what I want the output to be is:
z <- c(1, 1, 2, 0, 0)
I have tried this:
z <- ifelse(x == 1, 1
, ifelse(y == 1, 2, 0))
And I tried this (which seems really excessive to have to spell all of this out):
z <- ifelse(x == 1, 1
, ifelse(!is.na(x)
, ifelse(y == 1, 2
, ifelse(is.na(y), 0, NA))
, 0))
In any case that didn't work either... Both of those return:
> z
[1] 1 1 2 NA NA
Can someone please help me understand not only how to get the result I want but also how R treats NA when working with ifelse involving 2 vectors?
Thank you.
Aucun commentaire:
Enregistrer un commentaire