I am writing a report using knitr, with a template that runs analyses over multiple datasets (Section 1 of the MWE).
I can generate summaries of the results by assigning values to variables that I then "stitch together" into tables (Section 2 of the MWE). However, this approach is cumbersome and inflexible (e.g. lots of typing to change what specific bits appear in the table).
How can I automate the production of the summary tables?
-
Body of the report (MWE.Rnw):
documentclass{article} begin{document} tableofcontents newpage section{Run tests} In this section we run the tests using a template. <<run-all, include = FALSE>>= library(knitr) ## set data names data_names <- LETTERS[1:3] ## initialize var for data data_1 <- NULL data_2 <- NULL ## initialize vars for chi-squared test results cs_statistic <- NULL # X-squared cs_parameter <- NULL # df cs_p_value <- NULL # p-value ## initialize vars for binomial test results bt_p_value <- NULL # p-value bt_estimate <- NULL # estimate bt_ci_lower <- NULL # conf. int. lower bt_ci_upper <- NULL # conf. int. upper ## run template src = NULL for (i in data_names) src = c(src, knit_expand('analysis-template.Rnw')) @ Sexpr{paste(knit(text = src), collapse = 'n')} newpage section{Summary} In this section we summarise the results. <<summary-cs>>= tab <- data.frame(data_1, data_2, round(cs_statistic, 3), cs_parameter, round(cs_p_value, 3), row.names = data_names) colnames(tab) <- c("var 1", "var 2", "X-squared", "d.f.", "p-value") kable(tab, caption = "Summary results of $\chi^2$ tests") @ <<summary-bt>>= tab <- data.frame(data_1, data_2, round(bt_estimate, 3), round(bt_ci_lower, 3), round(bt_ci_upper, 3), round(bt_p_value, 3), row.names = data_names) colnames(tab) <- c("var 1", "var 2", "estimate", "95% conf. int. (lower)", "95% conf. int. (upper)", "p-value") kable(tab, caption = "Summary results of binomial tests") @end{document}
-
Template (analysis-template.Rnw)
subsection{Analysis of data {{i}}} <<analysis-{{i}}>>= ## generate data {{i}} (data_{{i}} <- sample(50:100, 2)) ## run tests (cs <- chisq.test(data_{{i}})) (bt <- binom.test(data_{{i}}[1], sum(data_{{i}}))) ## store results data_1 <- c(data_1, data_{{i}}[1]) data_2 <- c(data_2, data_{{i}}[2]) cs_statistic <- c(cs_statistic, cs$statistic) cs_parameter <- c(cs_parameter, cs$parameter) cs_p_value <- c(cs_p_value, cs$p.value) bt_estimate <- c(bt_estimate, bt$estimate) bt_ci_lower <- c(bt_ci_lower, bt$conf.int[1]) bt_ci_upper <- c(bt_ci_upper, bt$conf.int[2]) bt_p_value <- c(bt_p_value, bt$p.value) @
