When using R markdown if one wants to add text using code there are some simple ways to do it.
This is also true for tables, using the kable
command is
Use the pander package, which transform R objects into Pandoc's markdown:
> headers=list("We","are","your","friends")
> list_a=list("We","are","your","friends")
> library(pander)
> pandoc.header(headers)
# We
# are
# your
# friends
> pander(list_a)
* We
* are
* your
* friends
<!-- end of list -->
The first example used a helper function to create the headers, while the second demo simply called the generic S3 method, that can robustly transform a variety of R objects into markdown.
For people who want plots below each header, this is how I do it.
```{r, results="asis"}
for (i in headers){
cat("# ", i, "\n",
knitr::knit_child("plot.Rmd", quiet = TRUE), "\n")
}
```
In the plot.Rmd
put your plot code in it, e.g.
```{r}
# plotting code
```
This solution worked for me, compiling .Rmd to PDF in R 3.6.3:
```{r plot_loop_chunk, results='asis', tidy=FALSE}
for(i in 1:10){
cat("#", "Header", i, "\n")
print(<some loop-dependent plot>)
cat("\n")
cat("\n")
}
```
You need to construct your wanted markdown in R and use that together with the argument results = 'asis'
in your chunk options. Hence, something like the following will do what you want:
```{r, results='asis'}
headers <- list("We","are","your","friends")
for (i in headers){
cat("#", i, "\n")
}
```
The for
-loop here will create the output
# We
# are
# your
# friends
which is used directly as input in the .md document.