Generate Factor Levels

The function gl (‘generate levels’) is useful when you want to encode long vectors of factor levels: the syntax for the three arguments is this:

gl(‘up to’, ‘with repeats of’, ‘to total length’)

Here is the simplest case where we want factor levels up to 4 with repeats of 3 repeated only once (i.e. to total length=12):

gl(4,3)

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

Here is the function when we want that whole pattern repeated twice:

gl(4,3,24)

[1]  1  1  1  2  2  2  3  3  3  4  4  4  1  1  1  2  2  2  3  3  3  4  4  4

Levels:  1  2  3  4

If the total length is not a multiple of the length of the pattern, the vector is truncated:

gl(4,3,20)

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

If you want text for the factor levels, rather than numbers, use labels like this:

gl(3,2,24,labels=c("A","B","C"))

[1]  A  A  B  B  C  C  A  A  B  B  C  C  A  A  B  B  C  C  A  AyB  B  C  C
Levels:  A  B  C

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.