This question is related to this question, but not quite the same.
Say I have this data frame,
df <- data.frame(
id = c(1:6),
profession = c(1, 5, 4, NA, 0, 5))
and a string with human readable information about the profession codes. Say,
profession.code <- c(
Optometrists=1, Accountants=2, Veterinarians=3,
`Financial analysts`=4, Nurses=5)
Now, I'm looking for the easiest way to replace the values in df$profession
with the text found in profession.code
. Preferably without use of special libraries, unless it shortens the code significantly.
I would like my end result to be
df <- data.frame(
id = c(1:6),
profession = c("Optometrists", "Nurses",
"Financial analysts", NA, 0, "Nurses"))
Any help would be greatly appreciated.
Thanks, Eric
I personally like the way the
arules
package deals with this problem, using thedecode
function. From the documentation:Advantage is that the package also offers the functions
encode
andrecode
. Their respective purpose is straightforward, I believe.You can do it this way:
Note that I had to add a
0
entry in yourprofession.code
vector to account for those zeroes.EDIT: here is an updated solution to account for Eric's comment below that the data may contain any number of profession codes for which there are no corresponding descriptions:
I played around with it and this is my current solution using the
car
package.Still interest to if anyone have other suggestions for a solution. I would prefer to do it using only the base function in R.