# Re: [R] Build Design Matrix with avoiding loops

From: Martyn Byng <Martyn.Byng_at_nag.co.uk>
Date: Fri, 04 Jun 2010 16:30:26 +0100

Hi,

Something like

x = as.factor(rep(1:k,rep(n/k,k))
X = model.matrix(~x-1)

Might be what you are looking for

Martyn

I'd like to build a simple design matrix in a efficient way. I naively wrote the code below.

####
n = 15
k = 3
nbPerGrp = c(5,5,5)
xT <- list()

for (i in 1:k){

```      xT[[i]] <- rep(0, k)
xT[[i]][i] <- 1
```

}

X <- matrix(nrow = n, ncol = k) #design matrix

for (i in 1:nbPerGrp[1]){

X[i,] <- xT[[1]]
}

for (i in 1:k-1){

```      for (j in nbPerGrp[i]+1:nbPerGrp[i+1]){
X[j,] <- xT[[i]]
}}

for (i in 1:nbPerGrp[k]){
X[n - nbPerGrp[k] + i, ] <- xT[[k]]
```

}

X # That's I wanna get.
####

But as soon as n, k increase it takes too much time because of the loops.
Then my question is how can I get such a design matrix X without too much loops ? Which function I should look at ?

Thanks in advance for responding me,

Gildas

R-help_at_r-project.org mailing list