How to Create Ordered Factor in R

How to Create Ordered Factor in R, Will show you how to make ordered factors in R by using the ordered() function.

How to Create Ordered Factor in R

Let’s get started.

Example 1: Vector to Ordered Factor Conversion The ordered() Function

In this example, I’ll show how to convert a factor vector to an ordered factor.

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

fac <- factor(c("a", "a", "b", "c", "a"),          
levels = c("c", "a", "b"))
[1] a a b c a
Levels: c a b

Our factor, as you can see, has five elements and three-factor levels.

Data Science and Analytics Trends In 2023 » finnstats

Let’s look at our data object’s class.

[1] "factor"

Our data object has now become a factor.

We can now use the ordered function to convert our factor into an ordered factor:

ordered1 <- ordered(fac)                    
[1] c a b c a
Levels: c < a < b

The results are already slightly different (note the angle brackets between the levels).

Let’s look at the data type of our newly updated data object.

[1] "ordered" "factor"

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

It’s worth noting that we could achieve the same result by using the as.ordered function.

Example 2: Using the factor() function and the ordered argument, create an ordered factor

The R syntax below shows how to specify that a data object should be an ordered factor during the data object’s creation process.

Data Science applications in Retail » finnstats

To accomplish this, we must set the ordered argument within the factor function to TRUE.

ordered2 <- factor(c("c", "a", "b", "c", "a"), 
levels = c("c", "a", "b"),
ordered = TRUE)
[1] c a b c a
Levels: c < a < b

Let’s look at our data object’s class.

[1] "ordered" "factor"

Example 3: Check for Ordered Factors Using the function is.ordered()

The following example shows how to use the is.ordered function to determine whether a data object is an ordered factor.

Let’s start by applying the is.ordered function to the factor object we created at the start of Example 1.


The RStudio console returns FALSE, indicating that the data object my fac is not an ordered factor.

Let’s use the is.ordered function on the data object we created in Example 2:

[1] TRUE

This time, the is.ordered function returns TRUE, indicating that the data object ordered2 is an ordered factor.

Is It Difficult to Learn Data Science » finnstats

You may also like...

1 Response

  1. How can one create ordered factors in R, and what is the significance of using ordered factors in comparison to regular factors in statistical analysis?

Leave a Reply

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

five × 3 =