The gl() function in R is a convenient way to generate factors with a specified pattern of levels. It stands for “generate levels”, and it is often used in creating experimental designs or during data analysis for categorizing data into groups.
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: Basic usage
fact <- gl(3, 2, labels = c("Erlich", "Richard", "Gilfoyle"))
fact
Output
[1] Erlich Erlich Richard Richard Gilfoyle Gilfoyle
Levels: Erlich Richard Gilfoyle
Example 2: Specify labels
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: Changing the order of 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 seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.