【问题标题】:output table for multiple regressions多元回归的输出表
【发布时间】:2019-01-19 15:25:00
【问题描述】:

我运行了几次时间序列回归(每年一次),现在我想生成一个类似于 coef() 返回的表格,但也有显着性水平(星星)、R 平方和 F-每年的统计数据看起来有点像这样:

        b0    b1    b2    b3    b4    R-sq.    F-stat.
2010    ...*   
2011          ...
2012                ...**

到目前为止,我尝试了 memisc-package 中的mtable(),它给了我作为列的年份和作为行的系数,但我更希望结果是“转置”(如上)。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我编辑了我的问题。我对 R 的体验基本上为零。对此感到抱歉。
  • 没关系,欢迎来到 Stack Overflow!它只是帮助其他人帮助您了解到目前为止您已经尝试过什么以及您遇到问题的地方。你试过t(mtable())吗? (免责声明:我不知道这是否可行,但这是我的下意识反应)。在相关说明中,一些示例数据通过提供reproducible example 来帮助回答者。
  • 尝试t(mtable() 我得到“FUN(X[[i]], ...) 中的错误:下标越界”

标签: r


【解决方案1】:

由于我们无法访问您的数据或您用于运行模型的代码,因此我使用 mtcars 数据集创建了自己的虚拟模型:

data("mtcars")
model1 <- lm(mpg ~ wt + cyl, data = mtcars)
model2 <- lm(mpg ~ wt + cyl + hp, data = mtcars)

为了将来参考,您总是希望使用例如dput(head(my_dataframe, 20)) 来提供一些数据。您还应该提供更多用于获取当前位置的代码;事实上,重现您的问题所需的最少代码量。您可能想阅读How to Create a Great R Reproducible Example 了解更多信息;它只是帮助别人帮助你。

然后我装配了以下(笨拙的)功能,我认为它大致可以满足您的需求。无论如何,它应该让你朝着正确的方向开始:

get_row <- function(x, coef_names) {
    coef_mat <- coef(summary(x))
    these_coef_names <- rownames(coef_mat)
    rows <- match(coef_names, these_coef_names)
    p <- coef_mat[rows, 4]
    stars <- c("", "*", "**", "***")[(p < 0.05) + (p < 0.01) + (p < 0.001) + 1]
    coefs <- round(coef_mat[rows, 1], 3)
    output <- paste0(coefs, stars)
    output <- ifelse(grepl("NA", output), NA, output)
    return(output)
}
get_table <- function(...) {
    models <- list(...)
    if ( any(lapply(models, class) != "lm" ) ) {
        stop("This function has only been tested with lm objects.")
    }
    coef_names <- unique(unlist(sapply(models, variable.names)))
    coef_table <- t(sapply(models, get_row, coef_names))
    colnames(coef_table) <- coef_names
    return(coef_table)
}

get_table(model1, model2)

#      (Intercept) wt          cyl        hp      
# [1,] "39.686***" "-3.191***" "-1.508**" NA      
# [2,] "38.752***" "-3.167***" "-0.942"   "-0.018"

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2020-03-24
    • 1970-01-01
    • 2017-01-25
    • 2019-05-26
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多