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

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

    Based on the other answers which use converting to character I'm using the following function to concatenate factors:

    concat.factor <- function(...){
      as.factor(do.call(c, lapply(list(...), as.character)))
    }
    

    You can use this function just as you would use c.

    0 讨论(0)
  • 2020-11-28 10:58

    For this reason I prefer to work with factors inside data.frames:

    df <- data.frame(facs = as.factor(
          c("i", "want", "to", "be", "a", "factor", "not", "an", "integer") ))
    

    and subset it using subset() or dplyr::filter() etc. rather than row indexes. Because I don't have meaningful subset criteria in this case, I will just use head() and tail():

    df1 <- head(df, 4)
    df2 <- tail(df, 2)
    

    Then you can manipulate them quite easily, e.g.:

    dfc <- rbind(df1, df2)
    dfc$facs
    #[1] i       want    to      be      an      integer
    #Levels: a an be factor i integer not to want
    
    0 讨论(0)
提交回复
热议问题