[R] efficient use of lm over a matrix vs. using apply over rows

Duncan Murdoch murdoch at stats.uwo.ca
Sun Oct 5 16:28:10 CEST 2008


On 05/10/2008 10:08 AM, Mark Kimpel wrote:
> I have a large matrix, each row of which needs lm applied. I am certain than
> I read an article in R-news about this within the last year or two that
> discussed the application of lm to matrices but I'll be darned if I can find
> it with Google. Probably using the wrong search terms.
> 
> Can someone steer me to this article of just tell me if this is possible
> and, if so, how to do it? My simplistic attempts have failed.

You don't give a lot of detail on what you mean by applying lm to a row 
of a matrix, but I'll assume you have fixed predictor variables, and 
each row is a different response vector.  Then you can use apply() like 
this:

x <- 1:10
mat <- matrix(rnorm(200), nrow=20, ncol=10)

resultlist <- apply(mat, 1, function(y) lm(y ~ x))
resultcoeffs <- apply(mat, 1, function(y) lm(y ~ x)$coefficients)


"resultlist" will contain a list of 20 different lm() results, 
"resultcoeffs" will be a matrix holding just the coefficients.

lm() also allows the response to be a matrix, where the columns are 
considered different components of a multivariate response.  So if you 
transpose your matrix you can do it all in one call:

resultmulti <- lm(t(mat) ~ x)

The coefficients of resultmulti will match resultcoeffs.

Duncan Murdoch

Duncan Murdoch



More information about the R-help mailing list