7

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"
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

2 Answers2

9

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
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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
wibeasley
  • 5,000
  • 3
  • 34
  • 62
Mike
  • 11
  • 1