If I want to recode a variable in R using data.table
, what is the syntax? I saw some ans but didn't find them appropriate.
e.g. if I have the variable called gender
I want to recode gender 0 to unknown, 1 to male, 2 to female: here is how I tried:
Name <- c("John", "Tina", "Dave", "Casper")
Gender <- c(1, 2, 2, 0)
trips <- cbind.data.frame(Name, Gender)
trips[, gender = ifelse(gender == 0, "Unkown", gender == 1, "Male", gender == 2, "Female" )]
but I get an error
Put the rules in a table and do an update join:
Once you have a data.table then it would be most efficient to use a vectorized translation strategy. The
match
function provides a method of creating a "selection vector" for a choosing a item from a set of character possibilities:For this specific case, a simpler solution could be (ht to @Chinsoon):
You can do it this way
Two problems in your code:
:=
which is the assigning symbol for a column in data.tableifelse
, so you need anotherifelse
for the third case: if gender is not 0 then you need to test if gender is 1 to separate the Male and Female cases