Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...