Reputation: 1820
When using an ordered factor with NA as one of the levels, how to make NA the least (minimum) level?
Suppose I have a factor z
of type ordered. Adding NA
as one of the levels results in NA
appearing as the highest (maximum) level.
z <- factor(sample(LETTERS[1:3], 7, replace=TRUE))
z[4] <- NA
z <- ordered(z)
z <- addNA(z)
min(z) # A
max(z) # NA
How to order the levels so that min(z)
is NA
and max(z)
is "C"? The conventional manner of reordering drops the NA
:
z <- factor(z, levels = c(NA, "A", "B", "C"))
levels(z) # "A" "B" "C"
Upvotes: 3
Views: 578
Reputation: 79288
z=ordered(z,levels=c(NA,levels(z)),exclude=NULL)
> min(z)
[1] <NA>
Levels: A < B < C
> max(z)
[1] C
Levels: A < B < C
Upvotes: 0
Reputation: 50718
Use the exclude
and ordered
arguments of factor
:
set.seed(2017);
z <- factor(z, levels = c(NA, "A", "B", "C"), exclude = "", ordered = T)
#[1] <NA> A C A C B B
#Levels: <NA> < A < B < C
min(z)
#[1] <NA>
#Levels: A < B < C
max(z)
#[1] C
#Levels: A < B < C
Upvotes: 1