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 :

 “Pen”    “Pencil” “Brush”  “Pen”    “Brush”  “Brush”  “Pencil” “Pencil”

 FALSE

 “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 vectorsize = c("small", "large", "large", "small",         "medium", "large", "medium", "medium") # converting to factorsize_factor <- factor(size)                                     print(size_factor) # ordering the levelsordered.size <- factor(size, levels = c(  "small", "medium", "large"), ordered = TRUE) print(ordered.size)

Output:

 small  large  large  small  medium large  medium medium

Levels: large medium small

 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 sizesize = c("small", "large", "large", "small",         "medium", "large", "medium", "medium") sizes <- ordered(c("small", "large", "large",                   "small", "medium")) # ordering the levelssizes <- ordered(sizes, levels = c("small", "medium", "large"))   print(sizes)

Output:

 small  large  large  small  medium
Levels: small < medium < large

My Personal Notes arrow_drop_up