Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Level Ordering of Factors in R Programming

  • Last Updated : 27 Oct, 2021

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

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 factor() function. It takes a vector as input. c() function is used to create a vector with explicitly provided values. 

Example: 

R




x < - c("Pen", "Pencil", "Brush", "Pen",
        "Brush", "Brush", "Pencil", "Pencil")
 
print(x)
print(is.factor(x))
 
# Apply the factor function.
factor_x = factor(x)
levels(factor_x)

Output : 

[1] “Pen”    “Pencil” “Brush”  “Pen”    “Brush”  “Brush”  “Pencil” “Pencil”

[1] FALSE

[1] “Brush”  “Pen”    “Pencil”

In the above code, x is a vector with 8 elements. To convert it to a factor the function factor() is used. Here there are 8 factors and 3 levels. Levels are the unique elements in the data. Can be found using levels() function. 

Ordering Factor Levels

Ordered factors is an extension of factors. It arranges the levels in increasing order. We use two functions: factor() along with 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, size vector is created using c function. Then it is converted to a factor. And for ordering factor() function is used along with the arguments described above. Thus the sizes arranged in order.

The same can be done using the ordered function. The example for the same is as 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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!