Create parametric R markdown documentation?
I would use a combination of brew
and knitr
to achieve this. I would create a brew template called doc.brew
which looks like this
<% for (res in names(results)) { -%>
### Results for: <%= res %>
```{r}
plot(results[["<%= res %>"]]$x, results[["<%= res %>"]]$y)
```
<% } %>
You can now run the following code to get your desired output
results = list(
result1 = data.frame(x=rnorm(3), y=rnorm(3)),
result2=data.frame(x=rnorm(3), y=rnorm(3))
)
brew::brew('doc.brew', 'doc.Rmd')
knit2html('doc.Rmd')
How do I knit child documents with parameters into a main RMarkdown document?
What worked for me (derived from the documentation once I properly understood it.):
Instead of using the params
field in the YAML header, set the values of the parameters inside the main document and call cat
on the output of knitr::knit_child
. The below files achieved the desired result.
parameterized.Rmd
---
title: "Parameterized report"
output: html_document
---
```{r}
head(df[, 1:2])
```
main.Rmd
---
title: "Main report"
output: html_document
---
# mtcars
```{r mtcars, echo=FALSE, results='asis'}
df <- mtcars
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
# iris
```{r iris, echo=FALSE, results='asis'}
df <- iris
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
Knitting main.Rmd
applied the parameterized report to each dataframe.
Setting document title in Rmarkdown from parameters
Try to use a second YAML metadata block, and put the parameterized metadata in there.
I got the following code to work as expected (i.e., producing a document title from the list of params):
---
output: html_document
params:
set_title: "My Title!"
---
---
title: `r params$set_title`
---
The RMarkdown documentation notes that YAML metadata blocks are combined by Pandoc. Use the first block to define the parameter set, and the second one to use the parameters as metadata. Knitr will execute the R code to interpret the parameters in the second block.Then Pandoc will merge the metadata blocks together.
Update (2017):
This can be accomplished in a single block, like so:
---
output: html_document
params:
set_title: "My Title!"
title: "`r params$set_title`"
---
This works because the title comes after the params
definition. I put quotes around the in-line R code to prevent "Scanner errors".
Is it possible to create a self-rendering Rmarkdown document?
You can treat an Rmd file as an Rscript. For instance, assume that your Rmd file looks like this
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
You can then prepend the following code to that Rmd file
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
The trick here is q("no")
. This line terminates the R session, and, thus, whatever written after it will be ignored. Such an effect also means high flexibility for coding because you can write almost any valid R code before that q("no")
. The code above simply creates another temporary Rmd file with the same content as what is after q("no")
. Then, we rmarkdown::render
that temporary file and dump the output to the current directory.
The complete Rmd file looks like this
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Passing Parameters to R Markdown
In my case it worked, just had to change the indentation in the header and some names which are available in my folder...
Here my jnk.Rmd
---
title: "Liquidity Report"
output: pdf_document
params:
client: "NAMESPACE"
---
```{r plot, echo=FALSE, warning=FALSE}
cftest <- read.csv(params$client)
```
And this is what I called in the console : render('jnk.Rmd',params= list( client= "NAMESPACE"))
Passing parameters through an RMarkdown document?
I think the step you were missing was specifying the output filename so that each "vendor" would have its own file; otherwise, the same filename is overwritten each time leaving you with a single HTML document.
An example:
---
title: mtcars cyl
author: r2evans
params:
cyl: null
---
We have chosen to plot a histogram of `mtcars` where `$cyl` is equal to `r params$cyl`:
```{r}
dat <- subset(mtcars, cyl == params$cyl)
if (nrow(dat) > 0) {
hist(dat$disp)
}
```
Calling this with:
for (cy in c(4,6,8)) {
rmarkdown::render("~/StackOverflow/10466439/67525642.Rmd",
output_file = sprintf("cyl_%s.html", cy),
params = list(cyl = cy))
}
will render three HTML files, cyl_4.html
, cyl_6.html
, and cyl_8.html
, each with differing content:
Related Topics
Asymmetric Expansion of Ggplot Axis Limits
Output a Good-Looking Matrix Using Rendertable()
Displaying True When Shiny Files Are Split into Different Folders
Convert Quarter/Year Format to a Date
Ggplot2: Fix Colors to Factor Levels
Use Rollapply and Zoo to Calculate Rolling Average of a Column of Variables
Adding Percentage Labels on Pie Chart in R
Shapes and Linetypes in Ggplot
Format Date-Time as Seasons in R
How to Extend Letters Past 26 Characters E.G., Aa, Ab, Ac...
R Fast Single Item Lookup from List VS Data.Table VS Hash
How to Add a Page Break in Word Document Generated by Rstudio & Markdown
How to Use Loess Method in Ggally::Ggpairs Using Wrap Function
Dplyr::Do() Requires Named Function
Existing Function for Seeing If a Row Exists in a Data Frame