Parameterized RMarkdown File Name - r

I am trying to use 1 parameterized RMarkdown file to run 3 reports and output a different file name for each report (e.g. Report_A.html, Report_B.html, Report_C.html).
I have tried modifying the knit hook of the YAML, but am unable to get it to resolve the parameters.
I do not want to create a separate R file to loop through the parameters.
So far I have the following and the title is parameterized but the report name is Report_r params$site_2019-12-12.html
params:
site: "A"
title: "Report `r params$site`"
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile,
output_file=paste0("Report_", `r params$site`, "_", Sys.Date(),'.html')) })
Any suggestions would be appreciated - thank you!

Maybe don't call 'r ...' in :
output_file=paste0("Report_", `r params$site`, "_", Sys.Date(),'.html')) })
as in:
output_file=paste0("Report_", params$site, "_", Sys.Date(),'.html')) })

Related

Dynamically Name .Rmd Output File Based on Variable

Say I have an .Rmd file named "Process.Rmd", and within one chunk of the file I have a variable such as clientName <- "client AAA". Can I change the output filename from Process.pdf to Process_AAA.pdf? Specifically, the goal would be that I can simply change the clientName variable, strsplit() the client name, and use the second index of the split string in the filename.
eg. if I change clientName <- "myclient BBB", the output file would be Process_BBB.pdf.
I've tried changing the knit hook in the YAML header (example below), but I get errors because the clientName hasn't yet been defined.
title: "Process"
author: '***'
date: "`r format(Sys.time(), '%B %Y')`"
output:
pdf_document:
template: "/path/to/template.tex"
keep_tex: true
latex_engine: xelatex
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile,
encoding=encoding,
output_file= "`r paste0(
'Process_',
strsplit(clientName, ' ')[[1]][2],
'.pdf'
)`"
) })
When I move the knit hook to a portion of the .Rmd file after the clientName is defined, the output filename doesn't change.
I've also thought about creating a separate .R script with a function to render the document, but I need to reference the client name that's set in the .Rmd file; I haven't been able to source() a variable in that script from the .Rmd file...
Open to any suggestions

Instructing RMarkdown to use relative filepaths or stop shortening folder names

I have a parameterized RMarkdown PDF report that I am running from a Shiny dashboard (after copying it to a temporary directory).
Example code:
Shiny dashboard:
---
title: "Company Report Frontend"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r global, include=FALSE}
library(flexdashboard)
library(shiny)
```
### Select Company
```{r}
textInput('name', label ='Firm')
```
### Report
```{r}
uiOutput("downloadUI")
# Create the actual downloadButton
output$downloadUI <- renderUI( {
downloadButton("downBtn", "Download Report")
})
# Add download handling
output$downBtn <- downloadHandler(
filename = "full_report.pdf",
content = function(file) {
tempReport <- file.path(tempdir())
file.copy("test_report.Rmd", paste0(tempReport, "/test_report.Rmd"), overwrite = TRUE)
rmarkdown::render(paste0(tempReport, "/test_report.Rmd"), output_file = file,
params = list(input=input),
envir = new.env(parent = globalenv()), clean = FALSE,
knit_root_dir = tempReport,
)
}
)
```
test_report.RMD:
---
title: "Report"
header-includes:
\usepackage{graphicx}
params:
input: NA
output:
pdf_document:
latex_engine: xelatex
---
```{r}
input <- params$input
data(mtcars)
plot(mtcars$hp, mtcars$mpg)
title(input$name)
```
When I run it, it successfully produces the .tex file but then can't compile it. When I try to compile the .tex file directly in a LaTeX editor, I get undefined control sequence and Missing endcsname defined errors on any \includegraphics lines like this one:
\includegraphics{C:/User/LONGUS~1/Temp/file5b381fa967c8_files/figure-latex/unnamed-chunk-1-1.pdf}
where LONGUS~1 is a shortened folder name from the actual Windows username LONGUSERNAME.
The error goes away, and the PDF compiles, if I replace LONGUS~1 with LONGUSERNAME, or just point it to the relative filepath. LaTeX does tend to get finicky about filepaths sometimes.
How can I instruct RMarkdown to either avoid shortening folder names, or skip the absolute filepath and just use the relative? test_report.RMD compiles fine if I run it by itself (and specify a default input), so I'd guess this is something to do with the use of tempdir() or at least something in the render() function. But I really should keep the tempdir() stuff in the case of multiple simultaneous users of the shiny app. I did try removing the knit_root_dir option but that didn't fix it.
Any suggestions welcome. Thank you!

Bookdown Download for HTML single document

I have a bookdown book with multiple output formats.
I want the user to be able to download the content in multiple formats. This works wonders with PDF, EPUB and so on. But it does not work with single file HTML bookdown::html_document2 documents as they are rendered in the present working directory . and not the _book folder.
E.g., when I specify bookdown::git_book: ... it gets created in _book.
When I use bookdown::pdf_book: ... it also gets created in _book.
However, when I use bookdown::html_document2: ..., it gets created in ..
Setting output_dir for the single page document didn't work.
Do you know how to solve this?
MWE
## _bookdown.yml
book_filename: "The-book"
delete_merged_file: yes
## _output.yml
bookdown::gitbook:
split_by: rmd
config:
download:
- ["The-book.pdf", "PDF"]
- ["The-book.html", "HTML"]
bookdown::html_document2:
toc: true
bookdown::pdf_book:
keep_tex: no
dev: "cairo_pdf"
latex_engine: xelatex
and then in 01-intro.Rmd
# Intro
This is a test
I make book directly from a R script and this work for me:
bookdown::render_book(
input = "index.Rmd",
output_format = "bookdown::html_document2",
output_file = "_book/The-book.html"),
)
By making the book from R script you can start to have fun with name (like adding the date) and directory of the book, noting that if the directory is not _book you will need to create it before. With pdf output you can use output_dir to have the directory created for you, but it seems not to work and even conflict with output_file for html_document2. Ex:
## PDF report
bookdown::render_book(
input = "index.Rmd",
output_format = "bookdown::pdf_document2",
output_file = paste0("Proceedings-pdf-", format(Sys.time(), format = "%Y-%m-%d-%H%M%S"), ".pdf"),
output_dir = "Proceedings"
)
## HTML
dir.create("Proceedings", showWarnings = F)
bookdown::render_book(
input = "index.Rmd",
output_format = "bookdown::html_document2",
output_file = paste0("Proceedings/Proceedings-html-", format(Sys.time(), format = "%Y-%m-%d-%H%M%S"), ".html"),
)
Quarto is able to produce stand-alone html files (https://quarto.org/docs/output-formats/html-basics.html#self-contained). E.g.
---
project:
type: book
format:
html:
embed-resources: true
---
Note that this currently does not work if you specify an output path (see here).

Text (not syntax) highlighting in Rmarkdown/Papaja

I'm compiling a report using Papaja and Rmarkdown, and I want to highlight various text throughout. Doing so with latex or pure Rmarkdown is easy, but I'm receiving an "undefined control sequence" error when I compile the report to PDF using Papaja's application of Knitr.
A similar question about text highlighting within a single Rmarkdown file was answered here: RMarkdown / pandoc fails to knit Pdf with latex color commands. I'd like to know if an answer exists for multiple Rmarkdown files using Papaja.
I'll include a minimal example below.
1) File called papaja_file.Rmd
---
# https://crsh.github.io/papaja_man/index.html
title : "Some Title"
shorttitle : "HEADER"
author:
- name : "Name R Here"
affiliation : "1"
corresponding : yes # Define only one corresponding author
address : "Include addresss"
email : "randomemail#usa.edu"
affiliation:
- id : "1"
institution : "Any University"
author_note: |
....
abstract: |
Text here for abstract.
keywords : "Keyword1, keyword2, keyword3"
bibliography : ["references.bib"]
figsintext : no
figurelist : no
tablelist : no
footnotelist : no
lineno : yes
lang : "english"
class : "man"
output : papaja::apa6_pdf
---
```{r load_packages, include = FALSE}
library("papaja")
```
```{r analysis_preferences}
# Seed for random number generation
set.seed(42)
```
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.path = 'figures/', echo = TRUE, warning = FALSE, message = FALSE)
```
```{r child = 'child_document.Rmd'}
```
\newpage
# References
```{r create_references, echo = F}
r_refs(file = "references.bib")
```
\setlength{\parindent}{-0.5in}
\setlength{\leftskip}{0.5in}
Notice that it references a single child Rmarkdown document.
2) The child document with text, called child_document.Rmd
---
output:
pdf_document:
includes:
in_header: preamble.tex
---
One sentence without highlighting. \hl{Another with highlighting.}
3) The preamble, called preamble.tex
\usepackage{color}
\usepackage{soul}
\definecolor{lightblue}{rgb}{0.90, 0.95, 1}
\sethlcolor{lightblue}
Knitting the main papaja file produces the error. Removing the \hl command within the child document allows the pdf to compile without issue.
Result after putting YAML header within the main papaja document rather than the child:
The YAML header in your child document is not evaluated, c.f.
The master document, for example, consists of the YAML front matter and includes the children, which are themselves R Markdown documents without a YAML front matter.
https://crsh.github.io/papaja_man/tips-and-tricks.html#splitting-an-r-markdown-document
But you can include your preamble.tex in you master file using:
output:
papaja::apa6_pdf:
includes:
in_header: preamble.tex
c.f. https://github.com/rstub/stackoverflow/commit/a92a67d4721ee9c06e995b08adbf8cb89daebcb4
Result:

Chunk option class.output is not working on Error Message

I am preparing a tutorial for a course and I want to change the colour of the error to be red. I am using BookDown and gitbook as my output format. But I found that the option class.output is not working. I want to add a class to the output for the error message I get. How can I do that? You can use this as an example:
---
title: "Test Book"
author: "therimalaya"
site: bookdown::bookdown_site
output: bookdown::gitbook
---
# Hello World
```{r, error = TRUE, class.output="red"}
rnorm(-10)
```
This works if there is no error.
class.output is not applied to errors (see here).
Following this answer, I suggest you to use an error hook:
```{r error-hook, echo=FALSE}
knitr::knit_hooks$set(error = function(x, options) {
paste0(
"```{",
ifelse(is.null(options$class.error),
"",
paste0(" .", gsub(" ", " .", options$class.error))
),
"}\n",
x,
"\n```"
)
})
```
Now, you can use a "new" class.error option in your chunk.
```{r, error = TRUE, class.error="red"}
rnorm(-10)
```
Feel free to open a feature request here.
The ability to use custom CSS classes for errors, warnings, and messages was just added to knitr, so you will be able to use the following syntax.
```{r error = TRUE, class.error = "bg-danger text-danger"}
rnorm(-10)
```
Here I'm using Bootstrap classes, but you can pass any class(es) you need to class.error. The chunk options class.message and class.warning also work. Note that class.output is applied only to standard code outputs.

Resources