I was surprised to see that R will coerce factors into a number when concatenating vectors. This happens even when the levels are the same. For example:
> facs <- as.factor(c("i", "want", "to", "be", "a", "factor", "not", "an", "integer")) > facs [1] i want to be a factor not an integer Levels: a an be factor i integer not to want > c(facs[1 : 3], facs[4 : 5]) [1] 5 9 8 3 1
what is the idiomatic way to do this in R (in my case these vectors can be pretty large)? Thank you.
To combine two factor vectors, we can extract the unique levels of both the vectors then combine those levels. This can be done by using unique function. Also, we can set the levels of the original vectors to the combination of the levels, in this way, we can complete both the vectors with missing levels.
From the R Mailing list:
unlist(list(facs[1 : 3], facs[4 : 5]))
To 'cbind' factors, do
data.frame(facs[1 : 3], facs[4 : 5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With