Convert NA into a factor level

前端 未结 3 1071
感动是毒
感动是毒 2020-11-28 07:12

I have a vector with NA values that I would like to replace by a new factor level NA.

a = as.factor(as.character(c(1, 1, 2, 2, 3, N         


        
3条回答
  •  旧巷少年郎
    2020-11-28 08:11

    You can use addNA().

    x <- c(1, 1, 2, 2, 3, NA)
    addNA(x)
    # [1] 1    1    2    2    3    
    # Levels: 1 2 3 
    

    This is basically a convenience function for factoring with exclude = NULL. From help(factor) -

    addNA modifies a factor by turning NA into an extra level (so that NA values are counted in tables, for instance).

    So another reason this is nice is because if you already have a factor f, you can use addNA() to quickly add NA as a factor level without changing f. As mentioned in the documentation, this is handy for tables. It also reads nicely.

提交回复
热议问题