Re: [R] modify particular factor levels

From: Dieter Menne <dieter.menne_at_menne-biomed.de>
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.

Dieter

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

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: http://r.789695.n4.nabble.com/modify-particular-factor-levels-tp3450862p3452417.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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 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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive