我正在尝试按组创建一系列表格,我希望每个表格使用不同的变量迭代运行。我还想将anova的p值添加到表格的底部。我可以使用aov函数和kable函数轻松地创建单个表。我认为for循环可能如下工作:
#list of column names
varlist <- c("var1", "var2", "var3", "var4", "var5", "var6")
for (var in 1:6){
#anova
aov(varlist[[var]] ~ group, data=dc3)
#pull out pvalue for anova as string
pval <-paste("ANOVA P-Value:", round(summary(fit)[[1]][["Pr(>F)"]][[1]], 3))
# Create Table
Table <- dc3 %>% group_by(group) %>%
summarise(Mean = round(mean(varlist[[var]], na.rm = TRUE),2), SD = round(sd(varlist[[var]], na.rm = TRUE),2))
# Add Pvalue to bottom on table
kable(worst_arr_delays, "html") %>%
kable_styling(bootstrap_options = c("striped", "hover")) %>%
add_footnote(c(pval2), notation = "symbol")
}
理想情况下,这会给我六个与此类似的表:
答案 0 :(得分:1)
如果我理解你想做什么,我认为这段代码可以为你服务。
library(dplyr)
library(knitr)
library(kableExtra)
dc3 = data.frame(var1=rnorm(40,25,5),var2=rnorm(40,25,5),var3=rnorm(40,25,5),
var4=rnorm(40,25,5),var5=rnorm(40,25,5),var6=rnorm(40,25,5),
group=rep(c("gr.2","gr.3","gr.4","veh"),each=10))
res = NULL
for(i in 1:6){
fit <- aov(dc3[,i]~group,dc3)
pval <-paste("ANOVA P-Value:", round(summary(fit)[[1]][["Pr(>F)"]][[1]], 3))
# Create Table
Table <- dc3 %>% group_by(group) %>%
summarise(Mean = round(mean(dc3[,i],na.rm = TRUE),2), SD = round(sd(dc3[,i], na.rm = TRUE),2))
# Add Pvalue to bottom on table
res <- kable(Table,"html") %>%
kable_styling(bootstrap_options = c("striped", "hover")) %>%
add_footnote(c(pval), notation = "symbol")
print(res)
}