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

后端 未结 8 879
粉色の甜心
粉色の甜心 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:58

    This is a really bad R gotcha. Along those lines, here's one that just swallowed several hours of my time.

    x <- factor(c("Yes","Yes","No", "No", "Yes", "No"))
    y <- c("Yes", x)
    
    > y
    [1] "Yes" "2"   "2"   "1"   "1"   "2"   "1"  
    > is.factor(y)
    [1] FALSE
    

    It appears to me the better fix is Richie's, which coerces to character.

    > y <- c("Yes", as.character(x))
    > y
    [1] "Yes" "Yes" "Yes" "No"  "No"  "Yes" "No" 
    > y <- as.factor(y)
    > y
    [1] Yes Yes Yes No  No  Yes No 
    Levels: No Yes
    

    As long as you get the levels set properly, as Richie mentions.

提交回复
热议问题