Looping through code in knitr and rmarkdown

前端 未结 1 674
情深已故
情深已故 2021-01-03 16:37

I have been putting together reports using Knitr and rmarkdown. I love being able to output my R code in a reproducible R format, however I am continuously running into a li

相关标签:
1条回答
  • 2021-01-03 17:04

    For anyone finding this question, I finally found a reliable way to loop through markdown/latex code in a flexible manner, hope it helps. Basically you can put your rmarkdown header/footer information and then put each loop item specific code into the child. With one loop call it will generate as many child items as you want, reusing that code each time.

    Code for main.Rmd

    ---
      output: 
      pdf_document:
      includes:
    
      classoption: landscape
    geometry: margin=1.75cm
    ---
    
      `r  x1_list <- list(x1_front <- data.frame("col1" = rnorm(10), "col2" = rnorm(10)), x1_back <- data.frame("col1" = rnorm(10), "col2" = rnorm(10))) `
    `r  x2_list <- list(x2_front <- data.frame("col1" = rnorm(10), "col2" = rnorm(10)), x2_back <- data.frame("col1" = rnorm(10), "col2" = rnorm(10))) `
    `r master_list <- list(x1_list, x2_list) `
    
    
    ```{r include = FALSE}
    out = NULL
    for (i in 1:2) {
      num <- i
      out <- c(out,knit_child('child.Rmd'))
    }
    ```
    
    `r paste(out, collapse='\n')`
    

    Code for child.Rmd

    \newpage
    
    ## Name `r num`: First Table
    
    \vspace*{0.5in}
    
    ```{r echo = F, results = 'asis', message = F, warning = F, fig.width = 8, fig.height = 8, size = 'Large'}
    library(xtable)
    print(xtable(master_list[[num]][[1]]),type='latex',comment = FALSE,floating=FALSE)
    
    ```
    
    \newpage
    
    ## Manager `r num`: Second Table
    
    ```{r echo = F, results = 'asis', message = F, warning = F, fig.align = 'center', fig.width = 9, fig.height = 7, fig.show = 'hold', size = 'Large'}
    
    print(xtable(master_list[[num]][[2]]),type='latex',comment = FALSE,floating=FALSE)
    ```    
    
    0 讨论(0)
提交回复
热议问题