Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R gl() Function - Generating Factor Levels

R gl() Function - Generating Factor Levels

R Language Examples R Language Examples

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:

Example

3 treatments, each repeated 4 times

treatments

<-

gl

(

3

,

4

,

labels

=

c

(

"Control group"

,

"Drug A"

,

"Drug B"

)

)

print

(

"Experimental groups:"

)

print

(

treatments

)

Comparison with rep

rep(each = 4) is equivalent to gl(3, 4)

print

(

"Equivalent rep notation:"

)

print

(

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"

)

)

print

(

"Alternating pattern:"

)

print

(

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 R Language Examples