Dynamically change knitr .Rmd report text - r

I would like to dynamically change the text of an R markdown report template I'm using depending on certain inputs. I'm calling knitr from the PowerShell.
This is the input I would like to insert into the R markdown text Input:
{
"start": "1/21/2015",
"end": "1/23/2015",
"species: ["RBHS", "DBHS", "CBHS"]
}
.Rmd file
---
title: "Capture Report"
author: "Mitchell Gritts"
date: Sys.Date()
output: html_document
---
```{r load packages, include = FALSE}
LoadScripts()
```
## Capture Table
All SPECIESLIST captured between STARTDATE and ENDDATE are included
in the table. Data included in the table are Species, NDOW ID, Sex, Age,
Marks and Collar information.
SPECIESLIST, STARTDATE and ENDDATE are to be replaced with the values from the input.
Is there a way to do this with knitr or sweave. Or do I use search and replace functions to do this?

Related

Highlighting some references in RMarkdown documents?

Is it possible to emphasise (e.g., put in bold) some references that contain a particular string (e.g., the name of a particular author) in a papaja .Rmd document (where the refs are taken from a bib file and using the apa7.csl file)?
I can propose this solution based on pandoc lua filter which would work for not just pdf but also html output and doesn't require manual editing of latex or html file.
---
title: "The title"
bibliography: "r-references.bib"
output:
pdf_document:
pandoc_args: [ "--lua-filter", "ref-bold.lua"]
html_document:
pandoc_args: [ "--lua-filter", "ref-bold.lua"]
---
```{r setup, include = FALSE}
library("papaja")
r_refs("r-references.bib")
```
We used `R` [#R-base] and `Tidyverse` [#R-tidyverse] for all our analyses. Especially [#R-tidyverse] made things easy.
\vspace{10mm}
# References
ref-bold.lua
function Cite(el)
if pandoc.utils.stringify(el.content) == "[#R-tidyverse]" then
return (pandoc.Strong(el))
end
end
This demo bolds all of the reference to tidyverse package, if we would wanted to bold the reference to base-R, we would modify the second line in ref-bold.lua as pandoc.utils.stringify(el.content) == "[#R-base]" and all instances of references to base-R would be bold (highlighted).
pdf output
html output
A Lua-Filter would be the most elegant solution. If you use BibLaTeX and biber, you can use the general annotation feature (see this SO answer).
Include the following in your preamble:
\renewcommand*{\mkbibnamegiven}[1]{%
\ifitemannotation{bold}
{\textbf{#1}}
{#1}}
\renewcommand*{\mkbibnamefamily}[1]{%
\ifitemannotation{bold}
{\textbf{#1}}
{#1}}
In your bib-file, use the Author+an field to define which author to highlight:
#Misc{pawel2022power,
title = {Power Priors for Replication Studies},
author = {S Pawel and F Aust and L Held and E J Wagenmakers},
year = {2022},
eprinttype = {arxiv},
eprint = {2207.14720},
url = {https://arxiv.org/abs/2207.14720},
Author+an = {2=bold}
}
Now, render the R Markdown file with XeLaTeX, keep the intermediate files and the TeX file, and render the TeX file again using biber:
rmarkdown::render("paper.Rmd", clean = FALSE)
tinytex::xelatex("academic.tex", bib_engine = "biber")
Posting a solution in case it can be useful to others as well. We can first render the LaTeX file from the RMarkdown document, then find and replace all instances of the name to be emphasised, and finally generate the pdf from the modified LaTeX file.
# knitting the original Rmd file (with "keep_tex: true" in YAML)
rmarkdown::render(input = "some_file.Rmd")
# reading the generated LaTeX file
tex_file <- readLines(con = "some_file.tex")
# putting a particular author in bold in the references list
new_tex_file <- gsub(pattern = "James, W.", replace = "\\textbf{James, W.}", x = tex_file, fixed = TRUE)
# writing the (updated) LaTeX file
writeLines(text = new_tex_file, con = "some_file.tex")
# generating the pdf file (may need to be ran twice)
system(command = "xelatex some_file.tex")

knitr::is_word_output() to check if the current output type is word – just like knitr::is_latex_output() and knitr::is_html_output()

knitr::is_latex_output() and knitr::is_html_output() allow checking if the current output type LaTex or HTML respectively.
Is there an equivalent for Word as an output format?
If not, what would be the most simple to use workaround?
---
title: "MWE for different file formats in namespace:knitr"
output:
pdf_document: default
html_document: default
word_document: default
---
```{r}
if (knitr::is_html_output()) {
cat("HTML")
}
if (knitr::is_latex_output()) {
cat("LATEX")
}
if (knitr::is_word_output()) {
cat("WORD")
}
## Error: 'is_word_output' is not an exported object from 'namespace:knitr'
```
As of knitr 1.31 (released in January 2021), you can use knitr::pandoc_to() in either of the following ways:
```{r}
if (knitr::pandoc_to("docx")) {
cat("Word")
}
```
```{r, include=knitr::pandoc_to("docx")}
cat("Word")
```
To conditionally output literal text content (rather than R code), it's easiest to use an asis chunk (note that we need to use the echo option instead of include):
```{asis, echo=knitr::pandoc_to("docx")}
This will only appear in Word documents.
```
```{asis, echo=knitr::pandoc_to("docx", "pdf")}
This will be appear in Word and PDF documents.
```
Historical answer
In earlier versions of knitr, you can use an internal knitr function to get the type you want:
is_word_output <- function(fmt = knitr:::pandoc_to()) {
length(fmt) == 1 && fmt == "docx"
}

How do I insert a variable image file in a rmarkdown pdf

The problem is simple - How do I insert a variable filename into an rmarkdown PDF? I want to do this:
---
FNL = "image.png"
---
![Some Text](params$FNL)
only I need to pass in the value for FNL when calling rmarkdown::render
The purpose is to give the image a unique ID so that users get images marked for their session.
Anyone able to help with this?
Just use inline R evaluation (works for both HTML and PDF output):
---
title: "Example"
author: "Martin"
date: "March, 11 2017"
output: html_document
params:
img: NULL
---
`r sprintf("![A good boy](%s)", params$img)`
Then you can render the document with the image file by calling
rmarkdown::render("MyDocument.Rmd", params = list(img = "unnamed.png")).

kable_as_image knitr/kableextra rmarkdown

I am trying to use the function kable_as_image, which from my understanding will save the table as a image. My results though is not a table, dont know if I am doing something wrong as I cant find an example.
---
title: "Untitled"
author: "Test"
date: '2017-11-29'
output: pdf_document
---
```{r}
library(knitr)
library(kableExtra)
```
```{r}
kable_as_image(kable(head(iris)), filename = "~/Documents/.../.../pic")
```
#warning: kpathsea: gloss-$mainlang$.ldf: Unrecognized variable construct `$.'.
What my "picture" looks like:
Now I feel like kable_as_image is a somehow misleading name for the function. As explained in the doc, as least right now, it only works for latex tables, try kable_as_image(kable(..., format = "latex", booktabs = T), filename = "pic").

Passing function in rmarkdown parameter to render plots in html report

I am passing plots generated from shiny to rmarkdown to generate html report. The trouble is wordcloud and pie chart are being accepted in params in rmarkdown document.
Question : How to pass wordcloud and pie plots in rendered html via shiny ?
abc.Rmd
title: "Report using R Markdown"
subtitle: "ABC "
author: "Author name"
output:
prettydoc::html_pretty:
theme: architect
params:
wc : 'NULL'
table: 'NULL'
pie: 'NULL'
app.R(snippet)
rmarkdown::render(input = "report.Rmd",
output_file = "report.html",
params = list(wc=getWordcloud(),
table=getTab(),
pie=getPie()))
Note : getWordcloud(),getTab(),getPie() function are returning plots perfectly in shiny app.
You can't have as a parameter type a function.
See here in parameter type:
http://rmarkdown.rstudio.com/developer_parameterized_reports.html
All of the standard R types that can be parsed by the yaml::yaml.load function are supported including character, integer, numeric, and logical.
I strongly recommend to find a way to make your code working without the need to pass a function in the parameter. Maybe you can pass options of the function and include the function in the rmd?
But, there is ways to bypass that:
One is to use in the parameter the name of the function as a string and to use eval() to evaluate the string as code.
abc.Rmd
title: "Report using R Markdown"
subtitle: "ABC "
author: "Author name"
output:
prettydoc::html_pretty:
theme: architect
params:
wc : wc_function
table: table_function
pie: pie_function
eval(paste0(param$wc_function, "(", my_options_as_string, ")"))
app.R(snippet)
rmarkdown::render(input = "report.Rmd",
output_file = "report.html",
params = list(wc="getWordcloud",
table="getTab",
pie="getPie"))
Another one is to have another r script with the functions, called in the rmarkdown with source.
That way, you can pass the path of the file as a parameter and it allows you to get access to your function inside the rmarkdown (but it implies the name of the functions are fixed)

Resources