I would like to generate a number of reports from an r script. I would like to avoid the duplication needed when compiling from rmd files and I'd like to generate the reports from the r script itself if possible.
The script has a function which should generate each report from a list of dataframes where each report represents the processing of one dataframe. I just can't understand how to generate each report separately. At the moment the report shows all of the dataframes in one file
The original script is long so I have provided a minimal version below.
structure(list(a = structure(c(1L, 3L, 2L), .Label = c("boo",
"saa", "yaew"), class = "factor"), b = structure(c(2L, 3L,
1L), .Label = c("mfds", "shu", "ren"), class = "factor"), c = structure(c(2L,
1L, 3L), .Label = c("22", "23", "5345"), class = "factor")), .Names = c("a",
"b", "c"), row.names = c(NA, -3L), class = "data.frame")
ReportOp<-function(n) {
this_is_a_name <- n;
this_is_my_data <- ldf[[n]]
#' ---
#' author: Me
#' date:
#' ---
#+results='asis', echo=FALSE
knitr::kable(this_is_my_data, digits = 2)
#'
}
At the moment I am just generating the report with everything in it using thecompile notebook
button in R studio.
I tried using knitr::spin
on the above script as follows from a separate file:
library(knitr)
o=spin('/Users/sebastianzeki/Desktop/UntitledTBB.R')
knit2html(o,output="/Users/sebastianzeki/Desktop/out.html")
but again I only get one report outputted rather than three.
You would make a single rmarkdown parameterized report. Define the parameters in the YAML. You render the report by passing the parameters to rmarkdown::render()
in a list.
You'd run this over multiple sets of parameters by various means in r, loops, the apply
family (mapply
in this case), dplyr::do
, or the purrr:map()
functions. In this example, I use purrr::pmap()
.
Report.Rmd
---
title: "`r sprintf('mtcars %s vs. %s', params$variable1, params$variable2)`"
output: html_document
params:
variable1: "mpg"
variable2: "cyl"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(ggplot2)
```
#Plot
Crazy report text!
```{r cars}
ggplot(mtcars, aes_(x = as.name(params$variable1), y = as.name(params$variable2))) +
geom_point()
```
Render Function
render_report <- function(var1, var2) {
template <- "path_to/Report.Rmd"
out_file <- sprintf("report %s vs. %s", var2, var1)
parameters <- list(variable1 = var1,
variable2 = var2)
rmarkdown::render(template,
output_file = out_file,
params = parameters)
invisible(TRUE)
}
Running over multiple parameters.
library(purrr)
params_list <- list(list("mpg","mpg","mpg"),
list("drat","wt","qsec"))
pmap(params_list, render_report)
Output
Three html files, each named by the parameters, each with the scatterplot according to the parameters.
drat vs mpg
qsec vs mpg
wt vs mpg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With