Home > database >  Allocate a specific number to a column with charaters
Allocate a specific number to a column with charaters

Time:06-08

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?

CodePudding user response:

You could also use dplyr::recode and do it in one go:

Data <- Data1 %>%
  mutate(Style_Numeric = dplyr::recode(Style, 
                                Hallo = 1,
                                Bonjour = 3,
                                Bye = 4,
                                `Au Revoir` = 5,
                                Hello = 2))

CodePudding user response:

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))

CodePudding user response:

data.table option using fifelse:

library(data.table)
setDT(Data)
Data[, Style_Numeric := fifelse(Style == "Hallo", "1", 
                        fifelse(Style == "Hello", "2",
                        fifelse(Style == "Bonjour", "3",
                        fifelse(Style == "Bye", "4",
                        fifelse(Style == "Au Revoir", "5", Style)))))]
Data

Output:

   Name     Style Style_Numeric
1:    A     Hello             2
2:    B   Bonjour             3
3:    C     Hallo             1
4:    D       Bye             4
5:    E Au Revoir             5
  • Related