Dienstag, 22. November 2011

Recode a factor

Recoding a factor seems not to be a frequent activity of Ripley & Co. as it is astonishingly laboriously (because of the "else" part of it...).
The shortest trick I found so far is:

x <- factor(sample(letters, 20))
y <- x

levels(y) <- list(
  "good"=c("a","b","c"),
  "bad"=c("d","e","f"),
  "ugly"=c("h","m"),
  "else"=setdiff( levels(y), c("a","b","c","d","e","f","h","m") )
)
data.frame(x,y)

Anyone out there a better idea?