Factors in R are the data objects used to characterize the data and store it as levels. They can save both strings and integers. The relevel() function in R re-orders levels of the factor so that the level specified by the ref is first and the others are moved down.
Generate Factor Levels in R
To generate factor levels in R, use the gl() function. The gl() function produces the factors by defining the pattern of their levels. The gl() function takes two integers as input, which indicates how many levels and how many times each level and returns factors.
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
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 or not.
sv <- gl(3, 2, labels = c("Erlich", "Richard", "Gilfoyle")) sv
 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: R Program to generate factors
data <- gl(3, 4, 10, label = letters[1:12]) data app <- gl(3, 4, 10, label = letters[1:12], ordered = T) app
 a a a a b b b b c c Levels: a b c d e f g h i j k l  a a a a b b b b c c Levels: a < b < c < d < e < f < g < h < i < j < k < l
Changing the Order of Levels in R
To change the order of levels in R, apply the factor function again with the new order of the 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
 Erlich Richard Gilfoyle Gilfoyle Erlich Richard Levels: Erlich Gilfoyle Richard  Erlich Richard Gilfoyle Gilfoyle Erlich Richard Levels: Richard Erlich Gilfoyle
That is it for generating factor levels in R programming.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.