# Re: [R] Using lm with a matrix?

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
>> ydat
> [,1] [,2]
> [1,] 5 13
> [2,] 8 17
> [3,] 11 21
>> lrg <- lm(y~x)
>> lrg <- lm(ydat~xdat)
>> lrg
>
> Call:
> lm(formula = ydat ~ xdat)
>
> Coefficients:
> [,1] [,2]
> (Intercept) 2 9
> xdat1 3 4
> xdat2 NA NA

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