lundi 20 juillet 2020

Mutate and ifelse with NA and values from other variable in R [duplicate]

I have a df that looks something like this:

id <- c(1:8)
born.swis <-  c(0, 1, NA, NA, NA, 2, NA, NA)
born2005 <- c(NA, NA, 2, NA, NA, NA, NA, NA)
born2006 <- c(NA, NA, NA, 1, NA, NA, NA, NA)
born2007 <- c(NA, NA, NA, NA, NA, NA, NA, 1)
born2008 <- c(NA, NA, NA, NA, NA, NA, 2, NA)
born2009 <- c(NA, NA, NA, NA, NA, NA, NA, NA)
df <- data.frame(id, born.swis, born2005, born2006, born2007, born2008, born2009)

I'm trying to mutate born.swis based on the values of the other variables. Basically, I want the value bornswis to be filled with the value one of the other variables IF born.id is NA and IF it is not NA for that variable. Something like this:

id <- c(1:8)
born.swis <-  c(0, 1, 2, 1, NA, 2, 2,1)
df.desired <- data.frame(id, born.swis)

I tried several things with mutate and ifelse, like this:

df <- df%>%
  mutate(born.swis = ifelse(is.na(born.swis), born2005, NA,
                            ifelse(is.na(born.swis), born2006, NA,
                                   ifelse(is.na(born.swis), born2007, NA,
                                          ifelse(is.na(born.swis), born2008, NA,
                                                 ifelse(is.na(born.swis), born2009, NA,)
         )))))

and similar things, but I'm not able to reach my desired outcome.

Any ideas?

Many thanks!

Aucun commentaire:

Enregistrer un commentaire