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
modify particular factor levels
2 messages · Baptiste Auguie, Dieter Menne
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.