R gl() function - Generate factor levels
The R gl() function is used to quickly generate a factor (generate levels).
gl() is very useful in experimental design, allowing quick creation of group labels.
The syntax of the gl() function is as follows:
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
Parameter description:
nNumber of levels (how many groups).
kNumber of times each level is consecutively repeated.
lengthTotal length of the output factor (optional).
labelsName labels for the levels.
Example
# 3 treatments, each repeated 4 times
treatments <- gl(3, 4, labels = c("Control group", "Drug A", "Drug B"))
print("Experimental groups:")
print(treatments)
# Compare with rep
# rep(each = 4) is the equivalent of gl(3, 4)
print("rep equivalent:")
print(rep(c("Control group", "Drug A", "Drug B"), each = 4))
# Alternating mode (k=1)
groups <- gl(3, 1, length = 12, labels = c("A", "B", "C"))
print("Alternating mode:")
print(groups)
treatments <- gl(3, 4, labels = c("Control group", "Drug A", "Drug B"))
print("Experimental groups:")
print(treatments)
# Compare with rep
# rep(each = 4) is the equivalent of gl(3, 4)
print("rep equivalent:")
print(rep(c("Control group", "Drug A", "Drug B"), each = 4))
# Alternating mode (k=1)
groups <- gl(3, 1, length = 12, labels = c("A", "B", "C"))
print("Alternating mode:")
print(groups)
Executing the above code produces the following output:
[1] "实验分组:" [1] 对照组 对照组 对照组 对照组 药物A 药物A 药物A [8] 药物A 药物B 药物B 药物B 药物B Levels: 对照组 药物A 药物B [1] "rep 等效写法:" [1] "对照组" "对照组" "对照组" "对照组" [5] "药物A" "药物A" "药物A" "药物A" [9] "药物B" "药物B" "药物B" "药物B" [1] "交替模式:" [1] A B C A B C A B C A B C Levels: A B COther extensions
R Language Examples