[R] Build Design Matrix with avoiding loops

Martyn Byng Martyn.Byng at nag.co.uk
Fri Jun 4 17:30:26 CEST 2010


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}}



More information about the R-help mailing list