R gl


gl() function generates factors by specifying the pattern of their levels.
relevel() funtion re-orders levels of a factor so that the level specified by ref is first and the others are moved down. This is useful for contr.treatment contrasts which take the first level as the reference.

gl(n, k, length = n*k, labels = 1:n, ordered = FALSE)
relevel(x, ref, ...)

n: an integer giving the number of levels
k: an integer giving the number of replications
length: an integer giving the length of the result
labels: an optional vector of labels for the resulting factor levels
ordered: a logical indicating whether the result should be ordered or not
x: an unordered factor.
ref: the reference level.

> x <- gl(3,5)
> x
 [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3
Levels: 1 2 3


If length= is specified, then only elements of the length will be generated.

> length(x)
[1] 15
> x2 <- gl(3,5,10)
> x2
 [1] 1 1 1 1 1 2 2 2 2 2
Levels: 1 2 3


> x3 <- gl(3,5,10, labels=letters[1:10])
> x3
 [1] a a a a a b b b b b
Levels: a b c d e f g h i j
> gl(3,2,labels = c("green","red","yellow"))

[1] green green red red yellow yellow
Levels: green red yellow



Reorders the factor levels:

> v <- as.factor(c(3,5,"b","good","d"))
> v
[1] 3    5    b    good d
Levels: 3 5 b d good
> v2 <- relevel(v,"b")
> v2
[1] 3    5    b    good d
Levels: b 3 5 d good
> v2 <- relevel(v,"5")
> v2
[1] 3    5    b    good d
Levels: 5 3 b d good

Generate a factor with level ordered:

> x4 <- gl(3,5,20,ordered=T)
> x4
 [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 1 1 1 1 1
Levels: 1 < 2 < 3
endmemo.com © 2024  | Terms of Use | Privacy | Home