[R] Build Design Matrix with avoiding loops

Gildas Mazo gildas.mazo at curie.fr
Fri Jun 4 17:19:14 CEST 2010


Dear R users,

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



More information about the R-help mailing list