[R] modify particular factor levels

Dieter Menne dieter.menne at menne-biomed.de
Fri Apr 15 17:59:00 CEST 2011


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.



More information about the R-help mailing list