【问题标题】:Modelsummary: DV names and Model Names at the same time in differen rows?Modelsummary:DV 名称和模型名称同时在不同的行中?
【发布时间】:2021-12-17 20:17:30
【问题描述】:

我想知道如何使用 modelsummary 来组合模型名称和 DV 名称,就像在 Stata 中的 outreg2 中一样?这是代表:

    url <- 'https://vincentarelbundock.github.io/Rdatasets/csv/HistData/Guerry.csv'
dat <- read.csv(url)
models <- list(
  "OLS 1"     = lm(Donations ~ Literacy + Clergy, data = dat),
  "Poisson 1" = glm(Donations ~ Literacy + Commerce, family = poisson, data = dat),
  "OLS 2"     = lm(Crime_pers ~ Literacy + Clergy, data = dat),
  "Poisson 2" = glm(Crime_pers ~ Literacy + Commerce, family = poisson, data = dat),
  "OLS 3"     = lm(Crime_prop ~ Literacy + Clergy, data = dat)
)
modelsummary(models)

#N: DV names
modelsummary(dvnames(models), output = "flextable", estimate="{estimate}{stars}",
             statistic = 'statistic', stars = c('*' = .1, '**' = .05, '***'=0.01))
#N: Model names
modelsummary(models, output = "flextable", estimate="{estimate}{stars}",
             statistic = 'statistic', stars = c('*' = .1, '**' = .05, '***'=0.01))

以下是 DV 和型号名称组合表在 Stata 中的 outreg2 中的外观:

任何信息或建议将不胜感激!

【问题讨论】:

  • 如果您想添加具有因变量的不同行,您可能需要使用add_rows 参数:vincentarelbundock.github.io/modelsummary/articles/…
  • 嗨@Vincent,我查看了add_rows。有什么方法可以动态提取 dep 变量并动态构建行 tribble 以便我们没有预先指定 advacne 中的术语?这是唯一的方法吗?
  • 我使用 add_rows 只是为了使用您的代码的以下改编来更改条款:library(tibble) rows &lt;- tribble(~term, ~OLS, ~Logit) attr(rows, 'position') &lt;- c(0) modelsummary(models, add_rows = rows) 但它会引发错误:“add_rows”上的断言失败:必须至少有 1 行,但是有 0 行。

标签: r format modelsummary


【解决方案1】:

您可以use the add_rows argument 并创建自己的自定义函数来自动化该过程:

library(modelsummary)

insert_row <- function(x) {
    out <- c("DV:", names(dvnames(x)))
    out <- data.frame(as.list(out))
    attr(out, "position") <- 0
    return(out)
}

mod <- list(
    lm(mpg ~ hp, mtcars),
    lm(vs ~ hp, mtcars))

modelsummary(mod, add_rows = insert_row(mod))
Model 1 Model 2
DV: mpg vs
(Intercept) 30.099 1.217
(1.634) (0.150)
hp -0.068 -0.005
(0.010) (0.001)
Num.Obs. 32 32
R2 0.602 0.523
R2 Adj. 0.589 0.507
AIC 181.2 28.3
BIC 185.6 32.7
Log.Lik. -87.619 -11.134
F 45.460 32.876

【讨论】:

  • 效果很好,还提供了一些关于如何向包中添加功能的帮助!谢谢!
  • 不确定我是否应该提出一个新问题,但有没有办法以编程方式规定行位置?说出表格大小的最后一行还是 R2 之前的行?再次感谢您的回答 - 非常有帮助!
  • 是的。我上面的代码显示了如何设置“位置”。您还可以在add_rows(键入?modelsummary)的文档和网站上找到描述:vincentarelbundock.github.io/modelsummary/articles/…
  • 我多次查看该信息,唯一的例子是位置是预先确定的常量“attr(rows, 'position')
  • 有趣的想法,但很难实现。一种解决方法是生成表两次。第一次output="data.frame",然后您动态确定将其插入数据框中的位置,然后使用该信息准备您的add_rows。不理想,但不应超过 3-4 行代码。
猜你喜欢
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多