4
votes

I am new to R and trying to recode ordinal variables to numeric values. i have a variable named 'Founders_previous_company_employee_count' having 3 different entries as inputs-("Small","Medium","Large") which i am recording it to 1,2,3 values respectively. I tried using revalue function from plyr package using the below code

startupfull$employee_count_code<-as.numeric(revalue(startupfull$Founders_previous_company_employee_count,c("Small"=1, "Medium"=2, "Large"=3))) 

which works fine. However, i try using recode function in dplyr package, I am getting error message.

Code:

startupfull$prevcomp_empcount_code <-  as.numeric(recode(startupfull$Founders_previous_company_employee_count,c("Small"=1, "Medium"=2, "Large"=3)))

Error- Error: All replacements must be named

What am I doing wrong here?

3
I would prefer you using factor() to set the levels and then apply as.numeric() to it - joel.wilson

3 Answers

2
votes

This would be more appropriate as a comment on Aramis7d's answer above, but I don't have sufficient reputation to comment.

In case anyone is still confused after reading these answers (like I was), ignoring the fact that recoding to numeric is probably best done using as.numeric() and factor() as suggested by joel.wilson, the general solution that would also work if recoding to non-numeric values is to simply avoid wrapping the set of recoding pairs in c() when using dplyr's recode().

That is, instead of this:

    startupfull$prevcomp_empcount_code <-  
    as.numeric(recode(startupfull$Founders_previous_company_employee_count,
                    c("Small"=1, "Medium"=2, "Large"=3)))

Simply do this:

    startupfull$prevcomp_empcount_code <- 
    as.numeric(recode(startupfull$Founders_previous_company_employee_count,
                      "Small"=1, "Medium"=2, "Large"=3))
1
votes

For given inputs as

dput(x)

c("Small", "Large", "Medium", "Large")

try

as.numeric(recode(x, "Small" = "1", "Medium" = "2", "Large" = "3"))
0
votes
x = c("Small", "Large", "Medium", "Large")
as.numeric(factor(x, levels = c("Small", "Medium", "Large")))
[1] 1 3 2 3