[R] Regress a matrix on another matrix column by column

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Thu Mar 18 14:40:11 CET 2010


try this:

y <- matrix(rnorm(100*100), 100, 100)
x.a <- matrix(rnorm(100*100), 100, 100)
x.b <- matrix(rnorm(100*100), 100, 100)

M <- ncol(y)
models <- vector("list", M)
for (m in 1:M) {
     Dat <- data.frame(y = y[, m], x.a = x.a[, m], x.b = x.b[, m])
     models[[m]] <- lm(y ~ ., data = Dat)
}

Moreover and depending on what exactly you want to extract from these 
models, it may be even faster if you use lm.fit() instead of lm().


I hope it helps.

Best,
Dimitris


On 3/18/2010 12:35 PM, Frederick Ho wrote:
> Hi everyone,
>
> I have a response matrix (y) and two predictor matrices (x.a, x.b), how
> should i proceed if i want to regress y on x.a and x.b column by column?
>
> To be specific, what i want to do is:
>
> y[,1]~x.a[,1]+x.b[,1]
> y[,2]~x.a[,2]+x.b[,2]
> .
> .
> .
>
> I have tried lm(y~x1+x2) but it does not work as R treat that as:
>
> y[,1]~x.a[,1]+x.a[,2]+...+x.b[,1]+x.b[,2]+...
> .
> .
> .
>
> Thanks.
>
> Regards,
> Fred
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list