Create ordered level factors in R

Create ordered level factors in R, will demonstrate how to use R’s ordered() function to produce ordered factors.

Example 1: Ordered Factor from Vector Using the function ordered()

We’ll demonstrate how to convert a factor vector into an ordered factor in this example.

Create ordered level factors in R

To begin, we must first construct an example factor vector in R:

myfac <- factor(c("X", "Y", "Z", "Z", "X"),       
levels = c("Z", "Y", "X"))
[1] X Y Z Z X
Levels: Z Y X

As you can see, our factor has three-factor levels and five constituents.

Let’s verify our data object’s class:

[1] "factor"

Our data object is a factor at this moment.

Now that our factor has been transformed into an ordered factor, we can use the ordered function as follows:

my_fac_ordered1 <- ordered(myfac)                   
[1] X Y Z Z X
Levels: Z < Y < X

Already, the output differs slightly (see the angle brackets separating the levels).

Let’s examine our changed data object’s data type:

[1] "ordered" "factor"

We have changed our factor vector into an ordered factor vector, as you can see.

Keep in mind that we might use the as.ordered function to achieve the same outcome.

Joining Multiple Data Frames in R »

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

one × four =