Ordering Factor Values in R

Last Updated : 23 Jul, 2025

In this article, we will see how to order factor values in the R programming language.

We can order Factor values using the as.ordered() method. It is available in dplyr() package. So we have to load this package.

Syntax:

library(dplyr) 

Syntax:

as.ordered(factor_data)

Example 1 :

In this example, we will create a factor with 6 strings and order the values.

R
library(dplyr)

# create factor data with 5 strings
factor_data < - as.factor(c("sravan", "sravan", "bobby", 
                            "pinkey", "sravan"))

# display before ordering
print(factor_data)

# display after ordering
print(as.ordered(factor_data))

Output:

[1] sravan sravan bobby  pinkey sravan
Levels: bobby pinkey sravan
[1] sravan sravan bobby  pinkey sravan
Levels: bobby < pinkey < sravan

Example 2 :

In this example, we will create a factor with 6 integer elements and order the values.

R
library(dplyr)

# create factor data with 5 numeric values
factor_data < - as.factor(c(1, 2, 3, 2, 3))

# display before ordering
print(factor_data)

# display after ordering
print(as.ordered(factor_data))

Output:

[1] 1 2 3 2 3
Levels: 1 2 3
[1] 1 2 3 2 3
Levels: 1 < 2 < 3

We can also check whether the values in a factor are ordered or not. The is.ordered() is used to check it. It will return TRUE if the factor values are ordered. Otherwise, it will return FALSE.

Syntax:

is.ordered(factor_data)

Example:

Check whether the factor values are ordered or not.

R
library(dplyr)

# create factor data with 5 numeric values
factor_data < - as.factor(c(1, 2, 3, 2, 3))

# check values are ordered or not 
# before ordering
print(is.ordered(factor_data))

# order the values
order = as.ordered(factor_data)

# check values are ordered or not 
# after ordering
print(is.ordered(order))

Output:

[1] FALSE
[1] TRUE
Comment
Article Tags:

Explore