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 ) )
}
```
Thanks for your help!