[R] Build Design Matrix with avoiding loops

Erik Iverson eriki at ccbr.umn.edu
Fri Jun 4 17:36:53 CEST 2010


help.search("design matrix") will lead you to ?model.matrix ...

Gildas Mazo wrote:
> 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
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list