Ordering Factor Values in R
Last Updated :
01 May, 2022
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)
factor_data < - as.factor ( c ( "sravan" , "sravan" , "bobby" ,
"pinkey" , "sravan" ))
print (factor_data)
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)
factor_data < - as.factor ( c (1, 2, 3, 2, 3))
print (factor_data)
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)
factor_data < - as.factor ( c (1, 2, 3, 2, 3))
print ( is.ordered (factor_data))
order = as.ordered (factor_data)
print ( is.ordered (order))
|
Output:
[1] FALSE
[1] TRUE
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...