Ordering Factor Levels

Ordered factors levels are an extension of factors. It arranges the levels in increasing order. We use two functions: factor() and argument ordered().

Syntax:  factor(data, levels =c(“”), ordered =TRUE) 

Parameter: 

  • data: input vector with explicitly defined values.
  • levels(): Mention the list of levels in c function.
  • ordered: It is set true for enabling ordering.

Example: 

R




# creating size vector
size = c("small", "large", "large", "small",
         "medium", "large", "medium", "medium")
 
# converting to factor
size_factor <- factor(size)                                     
print(size_factor)
 
# ordering the levels
ordered.size <- factor(size, levels = c(
  "small", "medium", "large"), ordered = TRUE
print(ordered.size)


Output: 

[1] small  large  large  small  medium large  medium medium
Levels: large medium small

[1] small  large  large  small  medium large  medium medium
Levels: small < medium < large

In the above code, the size vector is created using the c function. Then it is converted to a factor. And for the ordering factor, the () function is used along with the arguments described above. Thus the sizes are arranged in order.

The same can be done using the ordered function. An example of the same is shown below:

Example: 

R




# creating vector size
size = c("small", "large", "large", "small",
         "medium", "large", "medium", "medium"
sizes <- ordered(c("small", "large", "large",
                   "small", "medium"))
 
# ordering the levels
sizes <- ordered(sizes, levels = c("small", "medium", "large"))   
print(sizes)


Output: 

[1] small  large  large  small  medium
Levels: small < medium < large

Level Ordering of Factors in R Programming

In this article, we will see the level ordering of factors in the R Programming Language.

Similar Reads

R – Level Ordering of Factors

Factors are data objects used to categorize data and store it as levels. They can store a string as well as an integer. They represent columns as they have a limited number of unique values. Factors in R can be created using the factor() function. It takes a vector as input. c() function is used to create a vector with explicitly provided values....

Ordering Factor Levels

...

Level ordering visualization in R

Ordered factors levels are an extension of factors. It arranges the levels in increasing order. We use two functions: factor() and argument ordered()....

Contact Us