0

Suppose I have this:

df$color <- ifelse(df$value == 1, "black", "red")

I.e. if the value == 1 in the value column of df, then we have black, otherwise we have red. This is fine.

But, how can I do this for values more than 2?

For instance, I want something like:

df$color <- if(df$name == 'Greg', 'red'), if(df$name == 'Tom', 'black'), 
  if(df$name == 'Beth', 'white')

But this syntax doesn't look right. Does anyone know how I can do this?

neilfws
  • 32,751
  • 5
  • 50
  • 63

3 Answers3

1

See dplyr::case_when().

For example:

library(dplyr)

df <- df %>%
  mutate(color = case_when(
    name == "Greg" ~ "red",
    name == "Tom" ~ "black",
    name == "Beth" ~ "white",
    TRUE ~ NA_character
  )
)
neilfws
  • 32,751
  • 5
  • 50
  • 63
1

One base R option using factor

within(
  df,
  color <- c("red", "black", "white")[as.integer(factor(name, levels = c("Greg", "Tom", "Beth")))]
)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

You can use dplyr::case_when() for multiple comparisons:

library(dplyr)

df <- tibble(name = c("Greg", "Tom", "Beth"))


df %>%
  mutate(color = case_when(name == "Greg" ~ "red",
                           name == "Tom" ~ "black",
                           name == "Beth" ~ "White"))
Paul
  • 2,877
  • 1
  • 12
  • 28