[R] modify particular factor levels

From: baptiste auguie <baptiste.auguie_at_googlemail.com>
Date: Fri, 15 Apr 2011 10:23:21 +1200

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,


R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 14 Apr 2011 - 22:33:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 15 Apr 2011 - 16:20:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive