mardi 2 mars 2021

How to do ifelse statements in R for more than two options?

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?

Aucun commentaire:

Enregistrer un commentaire