Having NA level for missing values with cut functi

2019-06-18 23:04发布

The cut function in R omits NA. But I want to have a level for missing values. Here is my MWE.

set.seed(12345)
Y <- c(rnorm(n = 50, mean = 500, sd = 1), NA)
Y1 <-  cut(log(Y), 5)
Labs <- levels(Y1)
Labs

[1] "(6.21,6.212]"  "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]" "(6.217,6.219]"

Desired Output

[1] "(6.21,6.212]"  "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]" "(6.217,6.219]" "NA"

标签: r cut
2条回答
Animai°情兽
2楼-- · 2019-06-18 23:30

You could use addNA

 Labs <- levels(addNA(Y1))
 Labs
#[1] "(6.21,6.212]"  "(6.212,6.213]" "(6.213,6.215]" "(6.215,6.217]"
#[5] "(6.217,6.219]" NA

In the expected output, you had character "NA". But, I think it is better to have real NA as it can be removed/replaced with is.na

 is.na(Labs)
 #[1] FALSE FALSE FALSE FALSE FALSE  TRUE
查看更多
forever°为你锁心
3楼-- · 2019-06-18 23:37

Changing the original MWE's third line to the following stores NA (actually ) in Y1 rather than the external vector Labs. This cleans up analytic tasks like making tables or building models. The NA is also still recognized by is.na().

Y1 <-  factor(cut(log(Y), 5), exclude=NULL)
is.na(levels(Y1))

result:

[1] FALSE FALSE FALSE FALSE FALSE  TRUE
查看更多
登录 后发表回答