Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can forcats::as_factor return an ordered factor?

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))
like image 222
Danny Avatar asked Oct 30 '22 02:10

Danny


1 Answers

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
like image 190
Aramis7d Avatar answered Nov 13 '22 00:11

Aramis7d