R base solution
You can use ifelse()
from base
for this. The functions arguments are ifelse(test, yes, no)
. Here an example:
(x <- sample(c("a", "b", "c"), 5, replace = TRUE))
[1] "c" "a" "b" "a" "a"
ifelse(x == "a", "Apple", x)
[1] "c" "Apple" "b" "Apple" "Apple"
If you want to recode multiple values you can use the function in a nested way like this:
ifelse(x == "a", "Apple", ifelse(x == "b", "Banana", x))
[1] "c" "Apple" "Banana" "Apple" "Apple"
Own function
Having many values that must be recoded can make coding with ifelse()
messy. Therefor, Ihere is an own function:
my_revalue <- function(x, ...){
reval <- list(...)
from <- names(reval)
to <- unlist(reval)
out <- eval(parse(text= paste0("{", paste0(paste0("x[x ==", "'", from,"'", "]", "<-", "'", to, "'"), collapse= ";"), ";x", "}")))
return(out)
}
Now we can change multiple values quite fast:
my_revalue(vec= x, "a" = "Apple", "b" = "Banana", "c" = "Cranberry")
[1] "Cranberry" "Apple" "Banana" "Apple" "Apple"
library(plyr); library(dplyr)
? – Insignia