Merge the Levels of a Factor

DESCRIPTION:
Merges old levels in a factor into new levels.

USAGE:
merge.levels(x, k)

REQUIRED ARGUMENTS:
x:
any object inheriting from factor (actually, any object with a suitable levels attribute).
k:
the number of new levels or the mapping from the current levels to the new ones. In the first case, should be an integer between 2 and the current number of levels. In the second case, can be a vector with 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).

OPTIONAL ARGUMENTS:
newlabels:
the names to use for the levels of the new factor. By default, the new levels are labelled by the old level names, pasted together. If 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.

VALUE:
a factor with the old levels merged into new levels as defined by k. Missing values are allowed and retained in the result.

HINT:
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().)

SEE ALSO:
levels , merge .

EXAMPLES:
Tfac <-c(a,b,c,d,e,f,g,h,a,b,c,d,e,f,g,h)

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