3

Is it possible to create a function that writes rmarkdown documents? For example, I would like to create 3 different htlml_documents with summary of different species from iris data set. Some like below (not working example)

markdown_function  <- function(function_input){

---
title: "Untitled"
date: "November 14, 2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r iris}
summary(iris[iris$Species == function_input, ])
```

}

   apply(data.frame(species = c('setosa', 'versicolar', 'virginica')), 1, markdown_function)
MLEN
  • 2,162
  • 2
  • 20
  • 36
  • 1
    The usual way to do that is to pass parameters in to the rmarkdown document. [Suggested dupe on Stack Overflow](https://stackoverflow.com/q/32479130/903061), [good introduction on the rmarkdown webpage](https://rmarkdown.rstudio.com/developer_parameterized_reports). – Gregor Thomas Nov 14 '18 at 15:20

1 Answers1

5

I'd recommend a slightly different approach. Create the RMarkdown file with a param value for species set in the file's yaml. Use that value for your filtering. Then in another script, use your apply function to knit the RMarkdown file for each species.

RMarkdown, saved as iris_params.Rmd

---
title: "Parameterized iris summary"
date: "November 14, 2018"
output: html_document
params: 
  species: setosa
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r iris}
species <- params$species
summary(iris[iris$Species == species, ])
```

Rendering script:

species <- c("setosa", "versicolor", "virginica")

sapply(species, function(x) {
  rmarkdown::render(input = "iris_params.Rmd", 
                    output_file = sprintf("iris_params_%s.html", x),
                    params = list(species = x))
})

This creates 3 HTML files, one for each of the species set as a parameter. Note that by default, the files will just be created with the same name as the input file, just the extension changed appropriately, so you need to create output file names for each parameter value. I'm doing this with sprintf and tacking the value of the species onto a base file name.

Output, iris_params_virginica.html:

html screenshot

camille
  • 16,432
  • 18
  • 38
  • 60