[R] apply lm() for all the columns of a matrix

Chuck Cleland ccleland at optonline.net
Wed Apr 9 13:49:20 CEST 2008


On 4/9/2008 6:55 AM, Costas Douvis wrote:
> Hi all,
> 
> My question is not really urgent. I can write a loop and solve the
> problem. But I know that I'll be in a similar situation many more times so
> it would be useful to find out the answer
> 
> Is there a fast way to perform linear fit to all the columns of a matrix?
> (or in the one dimension of a multi-dimensional array.) I'm talking about
> many single linear fits, not about a multiple fit. I thought that a
> combination of apply and lm would do it but I can't make it work

   The Details section of ?lm says:

If response is a matrix a linear model is fitted separately by 
least-squares to each column of the matrix.

   That seems to be what you are asking for.  Here is an example:

lm(as.matrix(iris[,1:3]) ~ iris$Species)

Call:
lm(formula = as.matrix(iris[, 1:3]) ~ iris$Species)

Coefficients:
                         Sepal.Length  Sepal.Width  Petal.Length
(Intercept)              5.006         3.428        1.462
iris$Speciesversicolor   0.930        -0.658        2.798
iris$Speciesvirginica    1.582        -0.454        4.090

> Thank you
> Kostas 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list