Search code examples
rrecode

Recoding Number to String R


I am new to R and I am trying to recode a numeric variable which is 1,2,3 to string. I have seen how to do it but I do not know why mine is not working, maybe it is because it should be from string to number? This is what I got, and thanks in advance!

cars$origin = as.factor(cars$origin)
cars$origin
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 3 2 2 2 2 2 1 1 1 1 1 3 1 3 1 1
[35] 1 1 1 1 1 1 1 1 2 2 2 3 3 2 1 3 1 2 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1
[69] 2 2 3 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 1 2 1 3 1 1 1
Levels: 1 2 3

cars$origin <- recode(cars$origin, "1='american';2='european';3='japan'")

Error: Argument 2 must be named, not unnamed


Solution

  • Function factor has argument labels for that:

    cars$origin = factor(cars$origin, 
       levels = c(1, 2, 3), 
       labels = c("american", "european", "japan"))