Keith Duong
Keith Duong

Reputation: 99

Why is `ifelse` returning NA?

I am using 'diamonds' dataset from 'tidyverse' package. My task is to define a new variable 'color2' with 2 levels 'good' and 'bad' of which 'good' corresponds the best 3 levels of 'color' and 'bad' corresponds the rest 4 levels. Here is my code:

diamonds %>% mutate(color2 = ifelse(levels(diamonds$color)[4],"bad","good")) 

However, NA is returned. Could someone tell me what went wrong with my code? Thank you so much!

Upvotes: 1

Views: 43

Answers (1)

danlooo
danlooo

Reputation: 10627

We can always use %in% to test for particular good levels. Since diamonds$color is an ordered factor, we can also use >=:

library(tidyverse)

is.ordered(diamonds$color)
#> [1] TRUE

diamonds2 <-
  diamonds %>%
  mutate(
    color2 = ifelse(color %in% c("I", "J"),"good","bad"),
    color3 = ifelse(color >= "I", "good", "bad")
  )

Upvotes: 1

Related Questions