Can forcats::as_factor return an ordered factor?

672 Views Asked by At

Can as_factor from forcats return an ordered factor? It seems like a missing feature if not although I haven't seen it reported as an issue on the GitHub page.

I have tried:

y <- forcats::as_factor(c("a", "z", "g"), ordered = TRUE)
is.ordered(y)
# FALSE

If I can't then is there any potential danger in doing:

y <- ordered(forcats::as_factor(c("a", "z", "g")))

Or would it be better to do:

y <- factor(c("a", "z", "g"), levels = unique(c("a", "z", "g")), ordered = TRUE))
1

There are 1 best solutions below

0
Aramis7d On

It appears this indeed is an unexpected behavior. forcats::as_factor is forcing it to be ordered as they appear, but somehow does not set the flag. But combining it with base::factor, it's not required to explicitly specify the ordering, just setting the flag seems to work fine.

y <- forcats::as_factor(c("a", "z", "g"))
y
[1] a z g
Levels: a z g

is.ordered(y)
[1] FALSE

k <- factor(y, c("a","z","g"), ordered = TRUE)
k
[1] a z g
Levels: a < z < g

is.ordered(k)
[1] TRUE

k2 <- factor( y, ordered = TRUE)
k2
[1] a z g
Levels: a < z < g

is.ordered(k2)
[1] TRUE

k3 <- factor(forcats::as_factor(c("a","g","z")), ordered = TRUE)
k3
[1] a g z
Levels: a < g < z

is.ordered(k3)
[1] TRUE