Sun Bee
Sun Bee

Reputation: 1820

in R, is it possible to have NA as the minimum of ordered factor levels?

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

Answers (2)

Onyambu
Onyambu

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

Maurits Evers
Maurits Evers

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

Related Questions