Another option is to list your variables using params
in the rmarkdown::render
function, see: http://rmarkdown.rstudio.com/developer_parameterized_reports.html.
First, declare and provide default values for parameters in the YAML of the rmarkdown document:
---
title: My Document
output: html_document
params:
df: !r data(mtcars); mtcars
ivs: ["cyl", "disp", "hp", "drat", "wt", "am", "qsec"]
dvs: ["mpg", "qsec"]
---
These are then accessible in the report body through the list params
:
Histograms
-------------------------------------
```{r}
for (v in union(params$ivs, params$dvs))
{
hist <- ggplot(params$df, aes_string(x=v)) + geom_histogram()
print(hist)
}
```
Finally, override the default values by passing a list of named arguments to rmarkdown::render
:
myDF <- read.delim("mydata.tab")
ivs <- c("iv1", "iv2", "iv3")
dvs <- c("dv1", "dv2", "dv3")
rmarkdown::render("MyDocument.Rmd",
params = list(df = myDF, ivs = ivs, dvs = dvs))
Since the YAML defines default values, one need provide only what one wishes to override, e.g.,
rmarkdown::render("MyDocument.Rmd", params = list(ivs = c("cyl", "wt")))
will still use the mtcars
dataset, but only plots histograms for cyl
, wt
, mpg
, and qsec
.