Re: [R] Using lm with a matrix?

From: Charilaos Skiadas <cskiadas_at_gmail.com>
Date: Sat, 07 Jun 2008 09:28:39 -0400

On Jun 7, 2008, at 8:13 AM, jonboym wrote:

>
> I'm trying to do a linear regression between the columns of
> matrices. In
> example below I want to regress column 1 of matrix xdat with
> column1 of ydat
> and do a separate regression between the column 2s of each matrix.
> But the
> output I get seems to give correct slopes but incorrect intercepts and
> another set of slopes with value NA. How do I do this correctly?
> I'm after
> the slope and intercept of each columns regression
>
>> xdat <- matrix(1:6,3,2)
>> xdat
> [,1] [,2]
> [1,] 1 4
> [2,] 2 5
> [3,] 3 6
>> ydat <- xdat
>> ydat[,1] <- xdat[,1]*3 +2
>> ydat
> [,1] [,2]
> [1,] 5 4
> [2,] 8 5
> [3,] 11 6
>> ydat[,2] <- xdat[,2]*4 - 3
>> yadt
> Error: object "yadt" not found
>> ydat
> [,1] [,2]
> [1,] 5 13
> [2,] 8 17
> [3,] 11 21
>> lrg <- lm(y~x)
> Error in eval(expr, envir, enclos) : object "y" not found
>> lrg <- lm(ydat~xdat)
>> lrg
>
> Call:
> lm(formula = ydat ~ xdat)
>
> Coefficients:
> [,1] [,2]
> (Intercept) 2 9
> xdat1 3 4
> xdat2 NA NA

Try this:

lapply( 1:2, function(i) lm( y~x, data=list(x=xdat[,i], y=ydat[,i]) ) )

Haris Skiadas
Department of Mathematics and Computer Science Hanover College



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 Sat 07 Jun 2008 - 13:32:07 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 Sat 14 Jun 2008 - 01:30:40 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