[R] modify particular factor levels

baptiste auguie baptiste.auguie at googlemail.com
Fri Apr 15 00:23:21 CEST 2011


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



More information about the R-help mailing list