In short: Is there a way to manipulate RMarkdown's metadata-list generated from the YAML header from within the following R-code chunks? To illustrate, I've tried the following:
---
title: "Untitled"
output: html_document
---
```{r}
rmarkdown::metadata$title <- "New title"
rmarkdown::metadata$title
```
This throws an error, though.
Error in rmarkdown::metadata$title <- "New title" :
Object 'rmarkdown' not found
Background
I'm working on a RMarkdown TeX-template. Some parts of the preamble need to be localized depending on the variable lang defined in the YAML header. My current approach is to check the value of metadata$lang and create a list of corresponding terms. I wanted to add the contents of the list to metadata and access the terms in the TeX-template via $loc_wordcount$, for example.
I think that the answer to this is no (though, I'm not 100% sure of that).
But, there is a different way to do it. You can use a parameterized report (https://bookdown.org/yihui/rmarkdown-cookbook/parameterized-reports.html).
The way to do that would be:
Create an rmarkdown file (e.g. called "input.Rmd") with parameters named param$value:
---
title: "params$new_title"
output: html_document
---
The rest of the report goes here.
Then render the report with a parameter passed in:
rmarkdown::render('input.Rmd', params = list(new_title = "New title"))
Related
---
params:
region: "UK"
date_week: "28_02_2022"
data_path_prefix: "C:\\Path\\To\\Folder\\"
data_path: `r paste0(params$data_path_prefix, params$date_week, "\\")`
title: "Summary Report: `r params$region`"
output:
html_document:
toc: true
df_print: paged
---
Hi all,
I am writing an RMarkdown report and I'm trying to keep any parameters that need to be manipulated each time the report is ran as parameters in the YAML header. Some parts of the report need to call a "date_week" parameter. Other parts need to call a filepath where the last directory is the date week. I would like to have one parameter for the date_week, and have that passed to my data_path parameter so I only have to change one thing.
Is it possible to do this? The code shown above is my attempt but the R code inserted does not evaluate.
Alternatively, are there other tidy ways to organise the code to achieve what I'm trying to do? e.g. would you define parameters in another file? I'm not sure what the best practises are.
Many thanks!
This is working for me:
---
params:
region: "UK"
date_week: "28_02_2022"
data_path_prefix: "C:\\Path\\To\\Folder\\"
data_path: !r paste0(params$data_path_prefix, params$date_week, "\\")
---
I have been using this solution to generate r-markdown reports from an interactive (Shiny) app.
Rather than generate and download a html file, I'm looking generate the corresponding .rmd file, since I want to be able to rerun the report with fixed settings at a later point in time.
To provide an example, using the template provided in the link, and for n=40, I want to generate a file containing the following code:
---
title: "Dynamic report"
output: html_document
params:
n: 40
---
```{r}
# The `params` object is available in the document.
params$n
```
In other words, a file in which the placeholder 'NA' from the template is replaced by the actual used value of 40.
Short of manipulating the yaml in the file directly, is there a way to set new parameters in a rmd template and generate the resulting .rmd file?
An extremely simple version to help with your parameters Rmarkdown question. This requires Rstudio. Instead of regularly knitting your document, you knit with parameters...
Now we get a GUI interface where we can specify the value we want, in this case we made it "numeric"
---
title: My Document
output: html_document
params:
input: numeric
---
`r params$input`
Which renders and includes our interactive parameter inside the Rmarkdown HTML rendered document. resources I used for research: resource 1 and resource 2. You can do wayy more with parameters, but this was a simple answer to help provide you with an answer to your question.
I am trying to include a table in a Word document but with no results. What I get in the resulting document is just a text list of the elements of the table including column names.
My code is organized in two scripts:
Script calling Markdown file KG-report.Rmd
rmarkdown::render("KG-report.Rmd", params = list(
pest.name = pest.name),
output_file = paste0("Report-", pest.name, ".docx")
Markdown script KG-report.Rmd
---
title: "Some title"
author: "me"
date: "`r Sys.Date()`"
output:
officedown::rdocx_document:
reference_docx: Simple_master_template_opinions.docx
tables:
style: Table
params:
pest.name: "Default pest"
---
```{r process-map, echo=FALSE, warning=FALSE, message=FALSE, fig.keep='all'}
# create and check directories
source("R_scripts\\PEST.PROFILE.check.pest.directories.r", local = knitr::knit_global())
# download distribution tables or load reviewed distribution table
source("R_scripts\\PEST.PROFILE.web.EPPO.distribution.table.r", local = knitr::knit_global())
knitr::kable(pest.kg.table)
etc...
After many tests and after following suggestions on word formatting (e.g. here) which did not solve the issue, it looks like the problem is related to looping on
rmarkdown::render()
If I do not use it the table is printed....
Is there any known issue about this or am I just using it in the wrong way?
Thank you
UPDATE - SOLUTION FOUND
In the end I was able to find a solution. It looked like the kable function was printing a html table in the word file which resulted in text with no table formatting. Adding the argument format = "pipe" solved the issue.
In the YAML header of a pandoc's markdown file, it's possible to write an abstract. I wonder if there is a way to change the word "abstract" in the rendered document to something else like either word "summary" or equivalent in another language.
If not, what alternatives could be suggested? I'm using R Markdown.
p.s. My question is related to this comment.
Yes. But not automatically. You would have to redefine the abstract environment to start with a different header, or at least redefine the \abstractname variable as article.cls has this:
\newenvironment{abstract}{%
\titlepage
\null\vfil
\#beginparpenalty\#lowpenalty
\begin{center}%
\bfseries \abstractname %%%% This what you need to redefine
\#endparpenalty\#M
\end{center}}%
{\par\vfil\null\endtitlepage}
So you can do something like the following minimal example:
---
title: "Test Document"
author: "Some User"
output: pdf_document
abstract: >
One or two sentences describing it all.
header-includes:
\renewcommand{\abstractname}{My Very Own Summary}
---
## R Markdown
This is an R Markdown document.
which does what you desire:
If your main interest is in localization of your document, you can add an lang meta value to your document. E.g., setting lang: lt will give "Santrauka" instead of "Abstract" in the produced PDF.
With one R markdown file, I would like to create different possible output pdf documents, where the output file name should be defined within the document. Is there any way to convince markdown to manipulate the output filename in such a way? Ideally I would like to pass the filename by an r chunk.
You can keep the simplicity of using the RStudio Knit button and reproducibility of a YAML header by using the undocumented knit hook to redefine what the button does (default function called is rmarkdown::render). The output_file parameter of the render function specifies the file name, so by setting it you override the standard behaviour of using the same prefix as the input filename.
e.g. to always output a file called myfile.pdf
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(dirname(inputFile), 'myfile.pdf')) })
The function can be an anonymous one-liner as well as imported from a package, as seen here with slidify.
You can set your own YAML headers (I don't know if this is generally advised anyway), accessible under rmarkdown::metadata$newheader but they don't seem available from within this sort of function as far as I can see.
As for passing file name in from an R chunk... if you're referring to code chunks below the YAML header, from my experience I don't think that's possible(?). Headers can contain inline R commands (single backtick-enclosed, starting with r), but seemingly not for this hook function.
Related:
Rmarkdown GitHub repo issue — output format-specific output_file
Blog post I wrote following this question [invalid link, domain for sale as of 20210216] / corresponding GitHub wiki notes
This is pretty much what I do:
rmarkdown::render('my_markdown_report.Rmd',
output_file = paste('report.', Sys.Date(),
'.pdf', sep=''))
I have three scripts - one pulls the data and process it, second created charts & tables for report. Third one creates report based on markdown file. Code you see above is the part of the third script
I played around with the Knitr-hook without fully understanding how it works and ran into an ugly workaround. The below coding seems to do the trick.
Would be nice if somebody can either explain why it works and/or if it can written less ugly.
For now I lost the shiny input screen but believe this can even be added later. The good thing is that the R-Studio Knit button can still be used.
Please note that the subtitle and the file name are both: This Works! even with space and exclamation mark. The file is saved as This Works!.pdf
The filename and subtitle are set by assigning the text to the object pSubTitle.
Note that the params are still in the YAML but are not resulting in a shiny popup screen as they are assigned in the Knitr-hook
---
params:
sub_title:
input: text
label: Sub Title
value: 'my_Sub_Title_and_File_Name'
title : "Parameterized_Title_and_output_file"
subtitle : "`r params$sub_title`"
output:
pdf_document:
keep_tex: false
knit: (
function(inputFile, encoding) {
pSubTitle <- 'This Works!'
rmarkdown::render(
input = inputFile,
encoding = encoding,
params = list(sub_title = pSubTitle),
output_file = pSubTitle) })
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. ....
My current solution for this and similar questions is through 2 scripts:
Script1: "xxx.md" file with flexible yaml header, similar to Floris Padt's. This header allows you to generate flexible pdf files with specified title, dates, and other features if you change the params. However, it could not specify flexible pdf names when you render it.
---
params:
feature_input: "XXXA"
date: "08/18/2022"
title: "`Test For `r params$feature_input``"
author: "You Name"
date: "`r params$date`"
output:
pdf_document:
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown and data process
```
#Get parameter from yaml head
input_para <- params$feature_input
input_para
```
Script2: "YYY.R", which specify params in xxx.md file, and specify pdf file names by output_file when rendering.
featureNames <- c("aaa", "bbb", "ccc")
setwd("path to xxx.md")
for (currentFeature in featureNames) {
rmarkdown::render("xxx.Rmd",
params = list(feature_input = currentFeature,
date = Sys.Date()),
output_file=paste0("output/",currentFeature))
}
You could update featureNames in yyy.R file, and run yyy.R to get the most flexible use of your xxx.md file.
This solution allows you to:
update yaml header parameters,
apply updated yaml parameters in your .md code chunk,
and save your pdf with specific and flexible names.