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

后端 未结 8 916
粉色の甜心
粉色の甜心 2020-11-28 10:12

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:

>         


        
8条回答
  •  囚心锁ツ
    2020-11-28 10:47

    Wow, I never realized it did that. Here is a work-around:

    x <- c(facs[1 : 3], facs[4 : 5]) 
    x <- factor(x, levels=1:nlevels(facs), labels=levels(facs))
    x
    

    With the output:

    [1] i    want to   be   a   
    Levels: a an be factor i integer not to want
    

    It will only work if the two vectors have the same levels as here.

提交回复
热议问题