Skip to content
Prev 43781 / 398513 Next

correction to the previously asked question (about merging factors)

Spencer Graves <spencer.graves at pdf.com> writes:
Actually, Sundars solution is exactly equivalent to the 

factor(c(as.character(F1),as.character(F2)))

that several have suggested, and which may actually be good enough for
the vast majority of cases. It is in fact the same thing that goes on
inside rbind.data.frame (that uses as.vector, which is equivalent).

If you really want something optimal, in the sense of not allocating a
large amount of character strings and comparing them individually to
a joint level set, I think you need something like this:

l1 <- levels(F1)
l2 <- levels(F2)
ll <- sort(unique(c(l1, l2)))
m1 <- match(l1, ll)
m2 <- match(l2, ll)
factor(c(m1[F1], m2[F2]), labels=ll)

or if you want to be really hardcore, bypass the inefficiencies inside
factor() and do

structure(c(m1[F1], m2[F2]), levels=ll, class="factor")

(People have been known to regret coding with explicit calls to
structure(), though...)