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

-----Original Message-----
From: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org] On Behalf Of Gildas Mazo
Sent: 04 June 2010 16:19
To: r-help_at_r-project.org
Subject: [R] Build Design Matrix with avoiding loops

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.

This e-mail has been scanned for all viruses by Star.\ _...{{dropped:12}}

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. Received on Fri 04 Jun 2010 - 15:32:47 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 04 Jun 2010 - 15:40:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive