Search code examples
rdplyrassign

Allocate a specific number to a column with charaters


I have a data frame that contains the column Style which contains only characters. I would like now to assign a predefined value to each type of character in this column.

The data looks like this:

structure(list(Name = c("A", "B", "C", "D", "E"), Style = c("Hello", 
"Bonjour", "Hallo", "Bye", "Au Revoir")), class = "data.frame", row.names = c(NA, 
-5L))

Now I would like to assign the value 1 to Hallo, 2 to Hello, 3 to Bonjour, 4 to Bye and 5 to Au Revoir.

I tried the following:

Data <- Data %>%
  mutate(Style_Numeric = ifelse(Style, "Hallo",  "1"))

However, when I check the data frame, the whole column Style_Numeric is empty. What do I need to change in the code?


Solution

  • ifelse works like this: ifelse(condition, yes, no). In this case you can write ifelse(condition = Style == "Hallo", yes = "1", no = NA). In your case your no statement would be another ifelse.

    Using case_when might be better in this case:

    Data %>%
      mutate(Style_Numeric = case_when(Style == "Hallo" ~  1, 
                                       Style == "Hello" ~ 2,
                                       Style == "Bonjour" ~ 3, 
                                       Style == "Bye" ~ 4, 
                                       Style == "Au Revoir" ~ 5))