gl Function in R (2 Examples)
In this tutorial you’ll learn how to generate a factor variable using the gl function in R programming.
Table of contents:
Let’s dive into it:
Example 1: Basic Application of gl() Function
In this example, I’ll illustrate how to apply the gl function to create a factor object in R.
Within the gl function, we have to specify the two integer arguments n and k. The argument n defines the number of levels; and the argument k specifies the number of replications.
Consider the following R code:
x1 <- gl(n = 3, # Apply gl function k = 5) x1 # Print output of gl function # [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 # Levels: 1 2 3
As you can see based on the previous output of the RStudio console, we have created a new data object called x1, which contains 15 elements and three different factor levels.
Example 2: Specify Labels within gl() Function
The following R code illustrates how to change the values (i.e. the labels) of a factor variable created by the gl function.
For this, we have to specify the labels argument as shown below:
x2 <- gl(n = 3, # Apply gl function k = 5, labels = letters[1:3]) x2 # Print output of gl function # [1] a a a a a b b b b b c c c c c # Levels: a b c
The previous R code has constructed a factor variable with the labels a, b, and c.
Video & Further Resources
In case you need further info on the R programming codes of this article, you could have a look at the following video on my YouTube channel. In the video, I’m explaining the topics of this article.
The YouTube video will be added soon.
In addition, you might read the other tutorials on this homepage. You can find a selection of tutorials below:
- Combine Factors without Changing Levels to Integer
- Convert Discrete Factor to Continuous Variable
- Group Factor Levels in R
- Get All Factor Levels of Vector & Data Frame Column
- Subset Data Frame Rows Based On Factor Levels
- Replace Values in Factor Vector or Column
- Convert Factor to Character Class in R
- Reorder Levels of Factor without Changing Order of Values
- Convert Character to Factor in R
- Drop Factor Levels of Vector & Data Frame
- Convert a Factor to Numeric in R
- Useful Commands in R
- All R Programming Examples
In this R tutorial you have learned how to specify a variable with factor levels using the gl function. If you have further questions on how to generate factors by setting a particular pattern of their levels, please tell me about it in the comments. In addition, please subscribe to my email newsletter to receive updates on new tutorials.
Statistics Globe Newsletter