0

我正在尝试按组创建一系列表,并且我希望每个表使用不同的变量迭代运行。我还想将 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")

   }

理想情况下,这会给我六个看起来与此类似的表:

在此处输入图像描述

4

1 回答 1

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)
}
于 2018-01-05T02:57:09.297 回答