1

我正在使用knitr, 使用模板编写报告,该模板对多个数据集进行分析(MWE 的第 1 节)。

我可以通过将值分配给变量来生成结果摘要,然后将这些变量“拼接”到表格中(MWE 的第 2 节)。然而,这种方法既麻烦又不灵活(例如,为了改变表中出现的特定位需要大量输入)。

如何自动生成汇总表?

  • 报告正文 (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}
    
  • MWE.Rnw调用的模板(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)
    @
    
4

0 回答 0