Create sections through a loop with knitr

rmarkdown loop chunks
looping through rmarkdown
create multiple reports with r markdown
r markdown chunk options
run rmarkdown from r script
r markdown plot in loop
r markdown manual table
r markdown cheat sheet

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.

Use loop to generate section of text in rmarkdown, This question is similar to that one, although it is LateX/RNW based. Besides, this answer demonstrates how to generate a rmarkdown� Using R, knitr, and beamer, I have created a pdf that contains a graph for each school in our district. I read in each graph using the \includegraphics command within a /foreach loop. I want to create a unique section name for each school using the R-variable 'school'. I want this section name to appear in the left hand Table of Contents.

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

Using knitr, beamer, and /foreach to produce unique section titles in , You use variable \i , which is TeX variable. The problem is, R knows nothing about it. Since R runs before TeX, your loop never reaches R. Instead you can make� In my thesis, I have found 79 different concepts I need to describe in detail in the appendix. I used R for the analysis, and I want to use knitr for creating that appendix. Each description follows the same basic "template" filled with the values for one concept.

I would actually suggest a solution that works a little bit different, i.e. create the R-Markdown file from an R-script and then render it from the same R-script:

# function that creates the markdown header
rmd_header <- function(title){
paste0(
"---
title: \"", title, "\"
output: html_document
---
"
)
}

# function that creates the Rmd code for the plots
rmd_plot <- function(my_list, my_fun){
paste0(
"
## ", names(my_list), "

```{r}
", deparse(substitute(my_fun)), "(", deparse(substitute(my_list)), "[[", seq_along(my_list), "]])
```
"
)
}

# your objects
my_list   <- list(foo = 1:3, bar = 4:7, baz = 8:12)
my_fun    <- plot
my_depth  <- 2 # I actually don't get what this is for

# now write everything into an rmd file
cat(rmd_header("Your Title")
    , rmd_plot(my_list, plot)
    , file = "test.rmd")

# and then create the html from that
rmarkdown::render("test.rmd", output_file = "test.html")

One thing to mention here: the indentation in the Rmd file does matter and when you copy the code here, make sure that R-Studio inserts it in the R-script as intended (because often it doesn't).

10.1 The function knitr::kable(), The kable() function in knitr is a very simple table generator, and is simple by You can also generate simple tables, or tables in HTML, LaTeX, and reStructuredText: As we mentioned in Section 4.7, a table can be cross- referenced when it has In general, when you generate output from a for -loop, we recommend that� At the end it says knitr::kable(coefs). This is a function from Knitr that outputs a nice table in markdown syntax. If you pass it a table or data frame in R, the result is a nice looking table. Quite a nice function to have. Loops with RMarkdown to repeat results with different data

Taking a similar approach to @Georgery... but in a somewhat over-engineered fashion (also somewhat more general?). Anyway, here it goes.

make_template <- function(my_list, my_fun, my_depth, my_title, my_output_type, my_template_file){

  require(glue)

  n <- length(my_list)


  # --- Rmd header ---
  make_header <- function(my_title, my_output_type){
    #
    my_header <- glue(
                      "---", "\n",
                      "title: ", deparse({my_title}), "\n",
                      "output: ", deparse({my_output_type}), "\n",
                      "---", "\n",
                      "\n",
                      "\n"
    )
    return(my_header)
  }

  # --- one section only ---
  make_section <- function(i){
    one_section <- glue(
                        "\n",
                        "\n",
                        paste0(rep("#", times = {my_depth}), collapse = ""), " ", names({my_list})[[i]], "\n",
                        "\n",
                        "```{{r}}", "\n",
                        paste0({my_fun}, "(", deparse({my_list}[[i]]), ")"), "\n",
                        "```", "\n",
                        "\n",
                        "\n"
    )
    return(one_section)
  }


  # --- produce whole template ---

  my_header <- make_header(my_title, my_output_type)

  all_my_sections <- ""
  for (i in seq_along(my_list)) {
    all_my_sections <- paste0(all_my_sections, make_section(i))
  }

  my_template <- paste0(my_header, "\n", "\n", all_my_sections)

  # --- write out
  cat(my_template, file = my_template_file)
}




# --- try it

make_template(my_list = list(foo = 1:3, bar = 4:7, baz = 8:12, glop = 1:7),
              my_fun = "plot",
              my_depth = 4,
              my_title = "super cool title",
              my_output_type = "html_document",
              my_template_file = "my_template_file.Rmd"
)

adding plots and markdown from a for loop � Issue #408 � yihui/knitr , The problem can be reproduced using the following listing: for( idx in seq(4) ) to host and review code, manage projects, and build software together. plot over and over again in the loop. knitr does not preserve identical� knitr will do that for you if the qplot is outside a loop, but (at least the version I have installed) doesn't detect this inside the loop (which is consistent with the behaviour of the R command line). – cbeleites unhappy with SX Aug 14 '12 at 17:37

[PDF] R Markdown Cheat Sheet, code in an R Markdown file to reproduce your work Learn more at rmarkdown. rstudio.com • RStudio IDE 0.99.879 • Updated: 02/16. More cheat sheets at Knit document to create report. Use knit button or Optional section of render (e.g.� I've been using the xtable package to create HTML tables out of R matrices. When I used the function kable in a loop, it didn't output anything. So I stared using the print function, which worked. The problem is that when I use the print function I get lots of "##" printed along the table HTML.

Use loop to generate section of text in rmarkdown, I need to produce a report that is composed of several sections, all sections look similar, with only some differences in data. The number of� Dashboards are nice tools when it comes to analyzing quickly changing data. Nevertheless, you may also use them for reporting purposes by taking snapshots. R has a nice library called flexdashboard which you can use for creating dashboards out of RMarkdown files. During a project at work we found a nice solution for dynamically rendering flexdashboard pages by using R Markdown child templates

27 R Markdown, 21.3.1 Modifying an existing object � 21.3.2 Looping patterns � 21.3.3 Rmd file to knitr, http://yihui.name/knitr/, which executes all of the code chunks The following sections dive into the three components of an R Markdown document in more Create one new R Markdown document for each of the three built-in formats:� R-Markdown is a great way to create dynamic documents with embedded chunks of R code. The document is self contained and fully reproducible which makes it very easy to share. This post will be the first in a multi part series on how to embed Plotly graphs in R-Markdown documents

Comments
  • Maybe stackoverflow.com/questions/21729415/… (I also have to do this, but haven't gotten around to it yet.)
  • Thanks Frank, that was very helpful! I think I made it work, though it still needs some testing, see below
  • I find the brew templates quite handy is such "loop over things" settings; see e.g. nice answers by @Ramnath: Loops with captions with knitr, Create parametric R markdown documentation?. Disclaimer: I have hardly followed the knitr development since the time of those answers...;)
  • I don't think it's hacky, it looks quite idiomatic to me actually. Thanks a lot! I think I can tweak this into an apply function in fact.
  • This is really cool, I think Lorenzo provides the flexible solution that is probably the idiomatic way to do this sort of things, but I can definitely see value in this to spit quick reports during data exploration, great job, and thanks to meriops for extending the approach too.
  • Really nice thanks, I think it deserves better parameter names and defaults that'd be a great adhoc function to create multiplot reports. I'd also make myfun more flexible because your approach wouldn't be very convenient to create sophisticated ggplots without wapping them in a named function beforehand