Curious G.
Curious G.

Reputation: 877

How consider NA using ifelse

I have this file:

Animal Bull   Breed     
Billy   1     Angus
Freddy  1     Nelore
Jone    NA    Nelore
Peter   2     Charoles

And I have some wrong breeds, and I needed to correct.

I needed the file this way:

 Animal Bull   Breed     
 Billy   1     Angus
 Freddy  1     Angus
 Jone    NA    Nelore
 Peter   2     Charoles

And I used this code:

df$Breed <- with(df, ifelse(Bull=='1', 'ANGUS', Breed))

But I got this data file:

Animal Bull   Breed     
Billy   1     Angus
Freddy  1     Angus
Jone    NA    NA
Peter   2     Charoles

When the Bull is NA the Breed disappears too. What happen? OBS: The Bull name is character.

Upvotes: 0

Views: 30

Answers (1)

Felix T.
Felix T.

Reputation: 530

Use is.na():

You could write a condition to consider missing values with is.na(). For example:

df$Breed <- with(df, ifelse(Bull=='1' & !is.na(Bull), 'Angus', Breed))


#>   Animal   Bull Breed   
#> 1 Billy       1 Angus   
#> 2 Freddie     1 Angus   
#> 3 Jone       NA Nelore  
#> 4 Peter       2 Charoles

Upvotes: 2

Related Questions