The gl() function in R is “used to generate factors by specifying the pattern of their levels”.
Syntax
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
Parameters
- n: It is an integer giving the number of levels.
- k: It is an integer giving the number of replications.
- length: It is an integer giving the length of the result.
- labels: It is an optional vector of labels for the resulting factor levels.
- ordered: It is a logical argument indicating whether the result should be ordered.
Example 1: How to use the gl() function
sv <- gl(3, 2, labels = c("Erlich", "Richard", "Gilfoyle"))
sv
Output
[1] Erlich Erlich Richard Richard Gilfoyle Gilfoyle
Levels: Erlich Richard Gilfoyle
In this example, we have defined 2 replications, which means it will repeat every element two times, and our levels are three: Erlich, Richard, and Gilfoyle.
Example 2: Specify Labels within gl() Function
data <- gl(3, 4, 10, label = letters[1:12])
data
app <- gl(3, 4, 10, label = letters[1:12], ordered = T)
app
Output
[1] a a a a b b b b c c
Levels: a b c d e f g h i j k l
[1] a a a a b b b b c c
Levels: a < b < c < d < e < f < g < h < i < j < k < l
Example 3: Change the order of levels in R
To change the order of levels in R, apply the “factor()” function again with the order of the new levels.
data <- c("Erlich", "Richard", "Gilfoyle", "Gilfoyle", "Erlich", "Richard")
factor_data <- factor(data)
factor_data
ordered_data <- factor(factor_data, levels = c("Richard", "Erlich", "Gilfoyle"))
ordered_data
Output
[1] Erlich Richard Gilfoyle Gilfoyle Erlich Richard
Levels: Erlich Gilfoyle Richard
[1] Erlich Richard Gilfoyle Gilfoyle Erlich Richard
Levels: Richard Erlich Gilfoyle
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.