Add extra level to factors in dataframe

后端 未结 5 1259
时光取名叫无心
时光取名叫无心 2020-11-30 04:09

I have a data frame with numeric and ordered factor columns. I have lot of NA values, so no level is assigned to them. I changed NA to \"No Answer\", but levels of the facto

5条回答
  •  盖世英雄少女心
    2020-11-30 04:43

    Since this question was last answered this has become possible using fct_explicit_na() from the forcats package. I add here the example given in the documentation.

    f1 <- factor(c("a", "a", NA, NA, "a", "b", NA, "c", "a", "c", "b"))
    table(f1)
    
    # f1
    # a b c 
    # 4 2 2 
    
    f2 <- forcats::fct_explicit_na(f1)
    table(f2)
    
    # f2
    #     a         b         c (Missing) 
    #     4         2         2         3 
    

    Default value is (Missing) but this can be changed via the na_level argument.

提交回复
热议问题