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

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

    Use fct_c from the forcats package (part of the tidyverse).

    > library(forcats)
    > facs <- as.factor(c("i", "want", "to", "be", "a", "factor", "not", "an", "integer"))
    > fct_c(facs[1:3], facs[4:5])
    [1] i    want to   be   a
    Levels: a an be factor i integer not to want
    

    fct_c isn't fooled by concatenations of factors with discrepant numerical codings:

    > x <- as.factor(c('c', 'z'))
    > x
    [1] c z
    Levels: c z
    > y <- as.factor(c('a', 'b', 'z'))
    > y
    [1] a b z
    Levels: a b z
    > c(x, y)
    [1] 1 2 1 2 3
    > fct_c(x, y)
    [1] c z a b z
    Levels: c z a b
    > as.numeric(fct_c(x, y))
    [1] 1 2 3 4 2
    

提交回复
热议问题