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:

Thanks for your help!
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:

Thank you to Christophe Dervieux for the pointer.
EDIT: An example of using separate child document is shown in the following image:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With