I haven’t managed to find a function that can recode vectors in a simple way, and that works for any class of vector. I think this function should be quite efficient despite the loop. ‘Vect’ is the vector you want to recode (which could be a variable in a data frame), ‘originals’ is a vector of values that appear in that vector, e.g. c(1, 2, NA), and replacements are the values you want to replace them with, e.g. c(NA, 7, 4). There is no need to include all unique values in the ‘originals’ vector.

recode <- function(vect, originals, replacements) { u <- rep(NA, length(vect)) for (i in 1:length(originals)) { if(is.na(originals[i])) { u[is.na(vect)] <- replacements[i] } else { u[vect == originals[i]] <- replacements[i] } } return(ifelse(vect %in% originals, u, vect)) }

Advertisements