【问题标题】:Linear Model in R for just a particular range of indexR中的线性模型仅适用于特定范围的索引
【发布时间】:2021-03-07 05:35:49
【问题描述】:

我想填空以生成一个带有参数 data 和 ind 的函数,该函数计算 ind 指示的原始数据子集的回归系数的点估计值。检查你的功能 输出和我的一样。

get_regression_coefs <- function(data, ind){
fit <- lm(____ ~ ____, data = ____[____, ])
coef(____)
}

get_regression_coefs(water_qual, 1:10)
## (Intercept) population median_income prop_children LO_health
## 3.5346120939 -0.0002160563 -0.0473334873 -2.3760093672 0.3081064103

这就是我所做的,但它没有产生正确的输出。

get_regression_coefs <- function(data, ind){
   
   fit <- lm(data[ind,1] ~ as.matrix(data[ind,-1]), data = data[ind, ])
   coef(fit)
 }
 
 get_regression_coefs(water_qual, 1:10)


                          (Intercept)    as.matrix(data[ind, -1])population 
                         3.5346120939                         -0.0002160563 
as.matrix(data[ind, -1])median_income as.matrix(data[ind, -1])prop_children 
                        -0.0473334873                         -2.3760093672 
    as.matrix(data[ind, -1])LO_health 
                         0.3081064103 

如何摆脱“as.matrix(data[ind, -1])”? 谢谢

【问题讨论】:

  • 将 coef() 读入对象并在 names() 上使用 stringr::str_replace() 或 strsplit() 函数。

标签: r regression lm


【解决方案1】:

如果它始终是您的第一列作为因变量:

get_regression_coefs <- function(data, ind){
   
   f = reformulate(response=colnames(data)[1],termlabels=colnames(data)[-1])
   fit <- lm(f, data = data[ind, ])
   coef(fit)
 }

 get_regression_coefs(mtcars,1:20)
(Intercept)         cyl        disp          hp        drat          wt 
 9.94145647  0.15637333 -0.01101635 -0.01341279  7.15255968  0.31382129 
       qsec          vs          am        gear        carb 
-0.11599981 -2.29398779  0.08732558 -0.49188785 -2.89550650 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2019-02-27
    • 2021-04-23
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多