Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

r - Convert NA into a factor level

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, NA)))
a
[1] 1    1    2    2    3    <NA>
Levels: 1 2 3

This works, but it seems like a strange way to do it.

a = as.factor(ifelse(is.na(a), "NA", a))
class(a)
[1] "factor"

This is the expected output:

a
[1] 1  1  2  2  3  NA
Levels: 1 2 3 NA
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use addNA().

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...