Generate Factors with specified Levels in R Programming – gl() Function

gl() function in R Language is used to generate factors by specifying the pattern of their levels.

Syntax:
gl(x, k, length, labels, ordered)

Parameters:
x: Number of levels
k: Number of replications
length: Length of result
labels: Labels for the vector(optional)
ordered: Boolean value to order the levels

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to generate factors
  
# Creating a factor
# using gl() function
x1 <- gl(2, 5)
  
# gl() function with
# length specified
x2 <- gl(3, 4, 12)
  
# Printing the factors
print(x1)
print(x2)

chevron_right


Output:

 [1] 1 1 1 1 1 2 2 2 2 2
Levels: 1 2
 [1] 1 1 1 1 2 2 2 2 3 3 3 3
Levels: 1 2 3

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to generate factors
  
# gl() function with
# length and labels specified
x1 <- gl(3, 4, 12, label = letters[1:12])
  
# gl() function with
# length, label and order specified
x2 <- gl(3, 4, 12, label = letters[1:12], ordered = T)
  
# Printing the factors
print(x1)
print(x2)

chevron_right


Output:

 [1] a a a a b b b b c c 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 c c
Levels: a < b < c < d < e < f < g < h < i < j < k < l
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.