如何在使用lm.beta修改对象后使用扫帚将lm摘要导出到数据框?

时间:2016-03-29 21:00:09

标签: r dataframe

我做了回归分析,然后使用lm.beta::lm.beta()对其进行了标准化。这样,它就会在结果中添加一个名为Standards的列,如下所示:

  lmfit <- lm(mpg ~ cyl + disp + hp + wt, data = mtcars)
  lmfit2 <- lm.beta::lm.beta(lmfit)
  summary(lmfit2)
            Estimate   Standardized Std. Error  t value  Pr(>|t|)
(Intercept) 40.82854   0.0000000    2.75747     14.807   1.76e-14    
cyl         -1.29332   -0.38324     0.65588     -1.972   0.058947
...

我想将其转换为数据帧,以便将其保存到Excel。我使用了来自tidy的{​​{1}}但是它与标题搞混了。

library(broom)

正如您所看到的,std.error列实际上是标准化的。如何修复标头?非常感谢!

1 个答案:

答案 0 :(得分:0)

正如我在评论中所述:

tidy.lm.beta <- function (x, conf.int = FALSE, conf.level = 0.95, exponentiate = FALSE, 
                                 quick = FALSE, ...) 
{
    if (quick) {
        co <- stats::coef(x)
        ret <- data.frame(term = names(co), estimate = unname(co))
        return(broom:::process_lm(ret, x, conf.int = FALSE, exponentiate = exponentiate))
    }
    co <- stats::coef(summary(x))
    nn <- c("estimate","std.estimate", "std.error", "statistic", "p.value")
    if (inherits(co, "listof")) {
        ret <- plyr::ldply(co, broom:::fix_data_frame, nn[1:ncol(co[[1]])], 
                                             .id = "response")
        ret$response <- stringr::str_replace(ret$response, "Response ", 
                                                                                 "")
    }
    else {
        ret <- broom:::fix_data_frame(co, nn[1:ncol(co)])
    }
    broom:::process_lm(ret, x, conf.int = conf.int, conf.level = conf.level, 
                         exponentiate = exponentiate)
}

lmfit <- lm(mpg ~ cyl + disp + hp + wt, data = mtcars)
lmfit2 <- lm.beta::lm.beta(lmfit)

然后:

> tidy.lm.beta(lmfit2)
         term    estimate std.estimate  std.error  statistic      p.value
1 (Intercept) 40.82853674    0.0000000 2.75746793 14.8065319 1.761402e-14
2         cyl -1.29331972   -0.3832400 0.65587675 -1.9718944 5.894681e-02
3        disp  0.01159924    0.2385278 0.01172681  0.9891215 3.313856e-01
4          hp -0.02053838   -0.2336456 0.01214677 -1.6908508 1.023791e-01
5          wt -3.85390352   -0.6256700 1.01547364 -3.7951783 7.589470e-04