Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create sections through a loop with knitr

See this reproducible example :

---
title: "test"
output: html_document
---

## foo

```{r}
plot(1:3)
```

## bar

```{r}
plot(4:7)
```

## baz

```{r}
plot(8:12)
```

I want to be able to automate the creation of these sections as I can't know how many they will be before going further in my analysis.

My input to get this would be :

my_list   <- list(foo = 1:3, bar = 4:7, baz = 8:12)
my_fun    <- plot
my_depth  <- 2

And the ideal answer (though I'm welcoming any improvement) would help me build a mdapply function so that I could just run:

```{r}
mdapply(X = my_list, FUN = my_fun, title_depth = my_depth)
```

And get the same output.

like image 498
Moody_Mudskipper Avatar asked Jul 03 '18 15:07

Moody_Mudskipper


1 Answers

R package pander can generate Pandoc's markdown on the fly.

The key is to use the chunk option results='asis' to tell R Markdown to render pander's output as Markdown. You just need to be careful to generate valid Markdown!

Try this:

---
title: "Test sections"
output: html_document
---

## A function that generates sections

```{r}
library(pander)

create_section <- function() {

   # Inserts "## Title (auto)"
   pander::pandoc.header('Title (auto)', level = 2)

   # Section contents
   # e.g. a random plot
   plot(sample(1000, 10))

   # a list, formatted as Markdown
   # adding also empty lines, to be sure that this is valid Markdown
   pander::pandoc.p('')
   pander::pandoc.list(letters[1:3])
   pander::pandoc.p('')
}
```

## Generate sections

```{r, results='asis'}
n_sections <- 3

for (i in seq(n_sections)) {
   create_section()
}
```

It still looks hackish, but Markdown has its limits...

like image 197
Lorenzo G Avatar answered Nov 15 '22 19:11

Lorenzo G