Recode a vector

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s