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
______________________________________________
R-help@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.