Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate factors, without them being converted to integer level?

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.

like image 958
Keith Avatar asked Aug 09 '10 19:08

Keith


People also ask

How do I combine two factors in R?

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.


1 Answers

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]) 
like image 172
fgregg Avatar answered Sep 28 '22 04:09

fgregg