1

I have a very simple question which I am sure there is an elegant answer to (I am also sure the title above is inappropriate). I have a vector of y values:

y = matrix(c(1, 2, 3, 4, 5, 6, 7), nrow=7, ncol=1)

which I would like to regress against each column in a matrix, x:

x = matrix(c(1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 4, 4, 4, 4, 4, 4, 4), nrow=7, ncol=3)

For example I would like to linearly regress the first column of x against y and then the second column of x against y until the last column of x is reached:

regression.1=lm(y~x[,1])
regression.2=lm(y~x[,2])

I would later like to plot the slope of these regression versus other parameters so it would be useful if the model coefficient parameters are easily accessible in the usual way:

slope.1 = summary(regression.1)$coefficients[2,1]

I am guessing a list using something like plyr but I am too new to this game to find the simplest way to code this.

4

2 回答 2

6
store <- mapply(col.ind = 1:ncol(x),function(col.ind){ lm(y~x[,col.ind]) })

然后,您可以使用以下方法访问斜坡:

> store[1,]
[[1]]
  (Intercept) x[, col.ind] 
 6.713998e-16 1.000000e+00 

[[2]]
  (Intercept) x[, col.ind] 
            8           -1 

[[3]]
  (Intercept) x[, col.ind] 
            4           NA 
于 2013-09-25T18:21:29.647 回答
2

另一种方式:

regression <- apply(x, 2, function(z)lm(y~z))

slope <- sapply(regression, function(z)unname(coef(z)[2]))

结果:

> slope
[1]  1 -1 NA
于 2013-09-25T18:26:49.317 回答