Like base::cut()
, but creates a level representing the missing values.
cut_with_nas(x, .missing = "Unknown", ...)
A numeric
or integer
vector to cut into factor levels. Required.
The name of the level representing the NA
values within x
.
further arguments passed to base::cut()
.
A factor
.
Discussed in the Stack Overflow question, "cut() a variable with missing values"
w <- c(0L, NA_integer_, 22:25, NA_integer_, 40)
breaks <- c(0, 25, 50)
labels <- c("lower", "upper")
cut_with_nas(w, breaks=2)
#> [1] (-0.04,20] Unknown (20,40] (20,40] (20,40] (20,40] Unknown
#> [8] (20,40]
#> Levels: (-0.04,20] (20,40] Unknown
cut_with_nas(w, breaks=breaks, labels=labels)
#> [1] Unknown Unknown lower lower lower lower Unknown upper
#> Levels: lower upper Unknown
cut_with_nas(w, breaks=breaks )
#> [1] Unknown Unknown (0,25] (0,25] (0,25] (0,25] Unknown (25,50]
#> Levels: (0,25] (25,50] Unknown
cut_with_nas(w, breaks=breaks , include.lowest=TRUE)
#> [1] [0,25] Unknown [0,25] [0,25] [0,25] [0,25] Unknown (25,50]
#> Levels: [0,25] (25,50] Unknown
cut_with_nas(w, breaks=breaks , include.lowest=TRUE, right=FALSE)
#> [1] [0,25) Unknown [0,25) [0,25) [0,25) [25,50] Unknown [25,50]
#> Levels: [0,25) [25,50] Unknown
cut_with_nas(w, breaks=breaks , right=FALSE)
#> [1] [0,25) Unknown [0,25) [0,25) [0,25) [25,50) Unknown [25,50)
#> Levels: [0,25) [25,50) Unknown