0

I have a for loop in R, inside of which I want to create R Markdown section headers and display (i.e., print) output from R functions. If I use {r results='asis'} at the start of the code chunk, I can get the section headers to work but the R output won't display properly. If I don't use results='asis' then the R output displays but the section headers won't work. How can I get R-created section headers and R output is the same code chunk?

Below is a short R Markdown script to demonstrate the issue. (It uses display of a matrix merely as a placeholder for various R functions such as summary(lm(...)); I am not specifically interested in displaying matrices.) An image of the knitr-ed output follows the script.

    ---
    title: "R Markdown Test"
    output:
      html_document:
        number_sections: yes
        theme: default
        toc: yes
        toc_depth: 4
        toc_float: no
        code_folding: hide
    ---
    
    # With*out* `results='asis'`
    
    ```{r}
    for ( i in 1:2 ) {
      cat("\n## Subsection",i,"\n")
      # knitr::asis_output( cat("\n## Subsection",i,"\n") ) # does not work
      print( matrix( i*(1:6), nrow=2 ) )
    }
    ```
    
    # With `results='asis'`
    
    ```{r results='asis'}
    for ( i in 1:2 ) {
      cat("\n## Subsection",i,"\n")
      print( matrix( i*(1:6), nrow=2 ) )
    }
    ```

The output looks like this: R Markdown output

Thanks for your help!

John K. Kruschke
  • 413
  • 3
  • 13
  • I've searched and searched and cannot find a solution. I did notice a comment saying knitr::asis_output cannot be used in loops (https://stackoverflow.com/questions/41133761/how-to-insert-markdown-in-the-middle-of-an-knitr-r-code-chunk#comment105434609_41135132), but why not? And is there a fix? – John K. Kruschke Sep 29 '21 at 17:23
  • I also asked this at RStudio Community (https://community.rstudio.com/t/results-asis-create-section-header-and-print-r-output-inside-a-for-loop/116676) – John K. Kruschke Sep 29 '21 at 17:54

1 Answers1

1

A response to my question at RStudio Community pointed me to the topic of child documents. By following the example of child documents I was able to create a solution to my question. My apologies that the solution is not elegant (IMO), but at least it works.

For more elaborate loop content, one would probably want to put the loop content into a separate text file, as shown in the example linked earlier. EDIT: I've appended an example of using a separate child document at the end of this answer.

Below is a solution using child documents. This is code appended to the code in my original post, so the section is numbered 3 in the output.

    # Using child documents

    Adapted from https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html#child-document

    ```{r results='asis'}
    res <- lapply( 1:2 , function(i) {
      knitr::knit_child( text=c(
        '## Subsection `r i`',
        '',
        '```{r}',
        'print( matrix(i*(1:6),nrow=2) )',
        '```',
        ''
      ) , envir=environment() , quiet=TRUE )
    })
    cat( unlist(res) , sep='\n' )
    ```

The result looks like this:

r markdown output

Thank you to Christophe Dervieux for the pointer.

EDIT: An example of using separate child document is shown in the following image: using separate child document

John K. Kruschke
  • 413
  • 3
  • 13