[R] modify particular factor levels

baptiste auguie
2011-04-14T22:23:21Z

Dear list,

I wish to modify programmatically only a few factor levels, according
to a named list. I came up with this function,

modify.levels <- function(f, modify=list()){

  ## levels that will not be changed
  names.old.levels <- setdiff(levels(f), unlist(modify))
  ## as a named list
  old.levels <- as.pairlist(names.old.levels)
  names(old.levels) <- names.old.levels
  ## union of unchanged levels and modified ones
  levels(f) <-  modifyList(old.levels, modify)
  f
}

f <- factor(LETTERS[1:4])
f2 <- modify.levels(f, list(aa = "A", cc="C"))

It seems to work, but the original order of the levels is changed.
Have I missed a better way of doing this manipulation?

Best regards,

baptiste