mardi 23 avril 2019

How to mutate with ifelse and missing values?

I'm trying to populate one column with the values in the same row in another column, where I have missing values. I'm trying to do this using dplyr and ifelse.

When I execute the code below, the entire column changes to NA.

df
animals isanimal
1     cat   animal
2     cat   animal
3     dog     NA
4     dog     NA
5   mouse   animal

The code that I've tried:

df <- df %>% mutate(isanimal = ifelse (df$isanimal == NA, df$isanimal == 
as.character(df$animals), df$isanimal == as.character(df$isanimal)))

What I get with this code:

> df
animals isanimal
1     cat   animal
2     cat   animal
3     dog     NA
4     dog     NA
5   mouse   animal

> df2
animals isanimal
1     cat       NA
2     cat       NA
3     dog       NA
4     dog       NA
5   mouse       NA

Any help will be appreciated (including help understanding why this doesn't work). Thanks!

Aucun commentaire:

Enregistrer un commentaire