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

From: Chuck Cleland <ccleland_at_optonline.net>
Date: Wed, 09 Apr 2008 07:49:20 -0400

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

______________________________________________
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.
Received on Wed 09 Apr 2008 - 12:41:56 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 09 Apr 2008 - 13:30:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive