starwars %>%
mutate(colors = ifelse(eye_color=='blue' | eye_color == 'yellow' | eye_color == 'white' | eye_color == 'orange' | eye_color == 'blue-gray' | eye_color == 'pink' | eye_color == 'green' | eye_color == paste('red',',','blue') | eye_color == paste('green',',','yellow') | eye_color == 'gold','light','dark'))
I'm trying to create new column according to eye_color column from dplyr::starwars
and I don't get a light value when I have two colors in one column all together. Please help me.
CodePudding user response:
If I understand correctly, you are trying to assign "light" to all the eye_color
you listed and "dark" otherwise.
In this case, you can use the function dplyr::case_when
like so:
starwars2 <- starwars %>%
# New variable
mutate (color = case_when(
eye_color=='blue' ~ 'light',
eye_color == 'blue-gray' ~ 'light',
eye_color == 'yellow' ~ 'light',
eye_color == 'white'~ 'light',
eye_color == 'orange'~ 'light',
eye_color == 'gold' ~ 'light',
eye_color == 'pink' ~ 'light',
eye_color == 'green'~ 'light',
eye_color == 'green, yellow' ~ 'light',
eye_color == 'red, blue' ~ 'light',
# then the else-output value
TRUE ~ 'dark')
) %>%
# check results
select(eye_color, color)
CodePudding user response:
You probably want something like this:
light_eye_colors <- c("blue", "yellow", "white") # etc...
starwars %>%
mutate(color = ifelse(eye_color %in% light_eye_colors, "light", "dark")
Having looked at the eye colors, this would be easier:
dark_eyes <- c("dark", "brown", "black")
starwars %>%
mutate(color = ifelse(eye_color %in% dark_eyes, "dark", "light")
You'll have to decide what you want to do about unknown
eye color.
CodePudding user response:
On the assumption that the only colors you'd class as "dark" are "brown", "black", and "dark", and the assumption that "unknown" should remain "unknown, this nested ifelse
statement should work:
starwars %>%
mutate(color = ifelse(grepl("dark|black|brown", eye_color),
"dark",
ifelse(eye_color == "unknown",
"unknown",
"light"))
)