merge.levels(x, k)
factor
(actually, any object with a suitable
levels attribute).
1
for all old levels
mapping into the first new level, a
2
mapping into
the second new level, and so on.
In the second case, can also be a list of the form
list(newlabel1=c(oldlabel1, oldlabel2, ...)
,
newlabel2=c(oldlabel3, ...), ...)
.
Any old labels not in the list are added to the end of the list.
You may also put new labels in the list (this means you can also add levels,
not just merge them).
k
is a list then the default for
newlabels
is
names(k)
and any
missing names are replaced by pasting together the old level names.
k
.
Missing values are allowed and retained in the result.
Sometimes, it is simpler to merge levels by assigning a new
levels attribute to the factor with non-unique values or by
assigning a list (in the form of
k
) as the new levels.
(The relevant method actually calls
merge.levels()
.)
Tfac <-rep(letters[1:8], 2) levels(Tfac) [1] "a" "b" "c" "d" "e" "f" "g" "h" merge.levels(Tfac,4) [1] a,b a,b c,d c,d e,f e,f g,h g,h a,b a,b c,d [12] c,d e,f e,f g,h g,h merge.levels(Tfac,c(1:5,6,6,6)) [1] a b c d e f,g,h f,g,h [8] f,g,h a b c d e f,g,h [15] f,g,h f,g,h Tfac1 <- Tfac levels(Tfac1) <- c(letters[1:5],rep("f",3)) #easier Tfac1 [1] a b c d e f,g,h f,g,h [8] f,g,h a b c d e f,g,h [15] f,g,h f,g,h merge.levels(Tfac,list(c("f","g","h"))) [1] a b c d e f,g,h f,g,h [8] f,g,h a b c d e f,g,h [15] f,g,h f,g,h Tfac1 <- Tfac levels(Tfac1) <- list(c("f","g","h")) Tfac1 [1] a b c d e f,g,h f,g,h [8] f,g,h a b c d e f,g,h [15] f,g,h f,g,h