R:多个模型并排的 Anova 输出

问题描述 投票:0回答:1

我正在尝试以与我通常对回归表所做的类似的方式获得几个方差分析的良好的可发表的输出。代码看起来有点像这样:

head(iris)
library(car)

# run model 1
lm1 <- lm(Sepal.Length ~ Species, data = iris)
summary(lm1)
a1 <- Anova(lm1)
# run model 2
lm2 <- lm(Petal.Width ~ Species, data = iris)
summary(lm2)        # long format (regression type output)
a2 <- Anova(lm2)    # short format (anova type output, which I need)

# what I usually do for regression outputs:
library(stargazer)
stargazer(lm1, lm2, type = "html", out ="iris.html")
# which yields a nice table with models side by side, including dependent variable names for each model; 
# this one I'd export as .html to Word and process there

# trying a similar joint table for anova type output:
stargazer(a1, a2, type = "html", out ="iris2.html")
# ... but that yields 2 separated tables and they can't be distinguished by dependent variables etc

# same problem here:
table <- rbind(a1, a2)
write.csv(as.data.frame(table), file = "iris2.csv")
# when I do this, I only get the same two tables underneath each other with their columnwise headers, 
# but without the distinguishing dependent variables 

由于我必须一遍又一遍地对更多模型执行此操作,因此我希望 Word 中的后期处理尽可能少。 我知道有使用 LaTeX 的非常好的解决方案,但不幸的是,由于合著者的原因,这些解决方案完全不可能。我尝试了

xtable
pixiedust
export
包,但无法获得我想要的结果。

希望有人能帮忙, 预先感谢!

r export output anova
1个回答
2
投票

如果您有兴趣定期生成 HTML 和 Latex 表,我建议您查看

library(kableExtra)
。这是关于 HTMLLatex 使用的优秀教程。

下面是如何创建 html 表格的示例。您将得到以下结果: ANOVA results table

# Convert ANOVA results into dataframes allows for easier name manipulation
a1_new <- data.frame(a1)
a2_new <- data.frame(a2) 

# Putting all into one dataframe/table
anova_results <- data.frame(cbind(c("Species", "Residuals", "Species", "Residuals"), 
                                  rbind(a1_new, a2_new))) 
colnames(anova_results) <- c("", "Sum Sq", "Df", "F value", "Pr(>F)")
row.names(anova_results) <- NULL

# create HTML table using kableExtra
library(kableExtra)
anova_results %>% kable("html", digits=2) %>% 
  kable_styling(bootstrap_options = "striped", full_width = F) %>% 
  pack_rows(., "Sepal Length", 1, 2) %>% # groups rows with label
  pack_rows(., "Petal Width", 3, 4) # groups rows with label

如果您希望这些值并排,这里有一种简单的方法来完成它......

anova_results2 <- data.frame(rbind(c("Sum Sq", "Df", "F value", "Pr(>F)", 
                                     "Sum Sq", "Df", "F value", "Pr(>F)"), 
                                   cbind(round(a1_new, 2), round(a2_new,2)))) 
colnames(anova_results2) <- c("", "", "", "","", "", "", "")
row.names(anova_results2)[1] <- ""

anova_results2 %>% kable("html") %>% 
  kable_styling(bootstrap_options = "striped", full_width = F) %>%
  add_header_above(c("", "Sepal Length" = 4, "Petal Width" = 4))

side by side

注意:为了获得正常运行的 Latex 表,您需要进行不同的修改。我确实认为,从长远来看,如果您想创建出版质量表,在 RMarkdown 中使用 Latex 可能是最好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.