# [R] How to generate factor levels with unequal numbers?

arun smartpink111 at yahoo.com
Fri May 10 20:58:55 CEST 2013

```Hi,
vec1<-factor(rep(c("A","B","C"),c(19,8,11)),levels=c("A","B","C"))
sapply(split(vec1,vec1),length)
# A  B  C
#19  8 11

#or you could change gl() function
gl.new<-function (n, k, labels = 1:n, ordered = FALSE) {
out<- numeric()
for(i in 1:n){
out<- append(out,rep(i,length.out=k[i]))
}
out<-factor(out)
levels(out)<- as.character(labels)
class(out)<- c(if (ordered) "ordered", "factor")
out
}
vec2<-gl.new(3,c(19,8,11),labels=LETTERS[1:3])
identical(vec1,vec2)
#[1] TRUE
gl.new(3,c(19,8,11),labels=LETTERS[1:3],ordered=TRUE)
#[1] A A A A A A A A A A A A A A A A A A A B B B B B B B B C C C C C C C C C C C
#Levels: A < B < C
A.K.

>If we use
>gl(6,2,24, label=c("ag", "cb", "cx", "ec", "hp", "mb"))
>We'll get 6 levels and 2 in each level
>
>But what if I want to generate factor levels with unequal numbers?
>For example, level: , A , B, C
>19 in A, 8 in B and 11 in C?
>
>Thanks!

```