summarize results dynamically produced by a template in R knitr -
i writing report using knitr
, template runs analyses on multiple datasets (section 1 of mwe).
i can generate summaries of results assigning values variables "stitch together" tables (section 2 of mwe). however, approach cumbersome , inflexible (e.g. lots of typing change specific bits appear in table).
how can automate production of summary tables?
body of report (mwe.rnw):
\documentclass{article} \begin{document} \tableofcontents \newpage \section{run tests} in section run tests using template. <<run-all, include = false>>= library(knitr) ## set data names data_names <- letters[1:3] ## initialize var data data_1 <- null data_2 <- null ## initialize vars chi-squared test results cs_statistic <- null # x-squared cs_parameter <- null # df cs_p_value <- null # p-value ## initialize vars 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 (i in data_names) src = c(src, knit_expand('analysis-template.rnw')) @ \sexpr{paste(knit(text = src), collapse = '\n')} \newpage \section{summary} in section summarise 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) called mwe.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) @
Comments
Post a Comment