Re: [R] modify particular factor levels

From: Dieter Menne <>
Date: Fri, 15 Apr 2011 08:59:00 -0700 (PDT)

baptiste auguie-5 wrote:
> I wish to modify programmatically only a few factor levels, according
> to a named list. I came up with this function..
> ....
> .....
> It seems to work, but the original order of the levels is changed.

The split-and-unite policy you use makes it a bit difficult to re-unite. You could keep a copy of the original sequence, but it's probably easier to do it via match. Note also that it also works for simple named vectors, which I would prefer (I hate these generic lists, lapply).

You should probably think of the error case below. Maybe it is best to keep it an error.


modify.levels <- function(f, modify=list()){   levs = levels(f)
  m = match(modify,levs)
  levs[m] = names(modify)

f <- factor(c(LETTERS[1:4],LETTERS[1:2]))# Added a few more to avoid special case

modify.levels(f, list(aa = "A", cc="C"))
modify.levels(f, c(aa = "A", cc="C"))
modify.levels(f, c(aa = "G", cc="C")) # Gives an error

View this message in context:
Sent from the R help mailing list archive at

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 15 Apr 2011 - 16:02:17 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:40:30 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive