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

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

    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
    

提交回复
热议问题