Jbnimble
Jbnimble

Reputation: 39

Creating Tables Iteratively with different columns

I am trying to create a series of tables by group and I would like to have each table run iteratively with a different variable. I would also like to add the p-value from an anova to the bottom of the table. I am able to do a single table easily using the aov function and the kable function. I thought a for loop might work as follows:

#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")

   }

Ideally, this would give me six tables that would look similar to this:

enter image description here

Upvotes: 0

Views: 85

Answers (1)

Rafael D&#237;az
Rafael D&#237;az

Reputation: 2289

If I am understanding what you want to do, I think that this code could serve you.

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)
}

Upvotes: 1

Related Questions