Programmatically insert text, headers and lists with R markdown

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.


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.


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
```

Tags:

Markdown

R