如何访问数据集的各个变量进行线性回归?

时间:2015-03-15 16:31:15

标签: r

我正在使用来自MASS包的波士顿数据集。

我需要分别使用其他13个预测变量来预测crim,并保存每个模型的斜率系数。

我如何自动化?

我不知道如何在for循环中访问数据集的变量。

我尝试过使用索引访问单个变量:

fit1 = lm(Boston[1]~Boston[2])

但它返回了这个:

Error en model.frame.default(formula = Boston[1] ~ Boston[2], drop.unused.levels = TRUE) : 
  invalid type (list) for variable 'Boston[1]'

我希望能够访问各个变量,以便使用for循环执行13个不同的lm() s:fit = Boston[i] ~ Boston[i+1]

3 个答案:

答案 0 :(得分:5)

reformulate()是使用指定预测变量设置公式的便捷方式:

 library("MASS")
 get.slope <- function(pred) {
     fit <- lm(reformulate(pred,response="crim"),data=Boston)
     ## unname() to avoid duplicating name of response
     return(unname(coef(fit)[2]))
 }
 sapply(names(Boston)[-1],get.slope)
 ##          zn       indus        chas         nox          rm         age 
 ## -0.07393498  0.50977633 -1.89277655 31.24853120 -2.68405122  0.10778623 
 ##         dis         rad         tax     ptratio       black       lstat 
 ## -1.55090168  0.61791093  0.02974225  1.15198279 -0.03627964  0.54880478 
 ##        medv 
 ## -0.36315992 

答案 1 :(得分:2)

lm(crim ~ zn, data = Boston)

lm(Boston$crim ~ Boston$zn)

使用

names(Boston) 

找出Boston

的列名

如果你真的想按索引获取列,获取第1列的所有行的语法是

Boston[,1]

答案 2 :(得分:1)

您也可以使用lapply

fits <- lapply(predictors, function(i) {temp <- lm(crim~get(i), data=Boston)$coefficients
                                        names(temp)[2]<- i
                                        return(temp)})
fits
[[1]]
(Intercept)          zn 
 4.45369376 -0.07393498 

[[2]]
(Intercept)       indus 
 -2.0637426   0.5097763 

.... and so on....

如果您只想要矢量或斜率系数,请尝试:

> setNames(sapply(fits, "[[", 2), predictors)
         zn       indus        chas         nox          rm         age         dis         rad 
-0.07393498  0.50977633 -1.89277655 31.24853120 -2.68405122  0.10778623 -1.55090168  0.61791093 
        tax     ptratio       black       lstat        medv 
 0.02974225  1.15198279 -0.03627964  0.54880478 -0.36315992 
相关问题