R gl() Function - Generating Factor Levels
The R gl() function is used to quickly generate a factor (generate levels).
gl() is very useful in experimental design, allowing you to quickly create grouping labels.
The syntax of the gl() function is as follows:
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
Parameter Description:
-
n The number of levels (how many groups).
-
k The number of consecutive repetitions of each level.
-
length The total length of the output factor (optional).
-
labels Name labels for the levels.
Example
3 treatments, each repeated 4 times
treatments
<-
gl
(
3
,
4
,
labels
=
c
(
"Control group"
,
"Drug A"
,
"Drug B"
)
)
(
"Experimental groups:"
)
(
treatments
)
Comparison with rep
rep(each = 4) is equivalent to gl(3, 4)
(
"Equivalent rep notation:"
)
(
rep
(
c
(
"Control group"
,
"Drug A"
,
"Drug B"
)
, each
=
4
)
)
Alternating pattern (k=1)
groups
<-
gl
(
3
,
1
,
length
=
12
,
labels
=
c
(
"A"
,
"B"
,
"C"
)
)
(
"Alternating pattern:"
)
(
groups
)
The output of the code above is:
[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 C
R Language Examples