Thanks to parameterized reports support by Rmarkdown, it is easy to make an .Rmd file rendered with parameters as follows (this example is from here):
---
title: "`r params$dynamictitle`"
params:
dynamictitle: My report
reportdate: !r Sys.Date()
date: "`r params$reportdate`"
---
This would be fine to knit to a .html file, but cannot be rendered in blogdown, with the following error:
Quitting from lines 2-5 ()
<simpleError in eval(parse_only(code), envir = envir): object 'params' not found>
I want to know whether there is a workaround way to make an .Rmd file parameterized?
Related
I want to change the output of Rmarkdown filename based on what the parameter value using the Knit with parameter option.
Here's an example:
---
title: "Output Filename by Parameter"
author: "myself"
date: "`r Sys.Date()`"
output: html_document
params:
exp:
label: "Experiment: "
value: draft
input: select
choices: [draft, review, final]
knit: >
(function(input, ...) {
metadata <- rmarkdown::yaml_front_matter(input)
output_file <- paste0('exp_', metadata$params$exp$value, '.html')
rmarkdown::render( input, output_file = output_file )
})
---
Some texts...
When I executed this with 'Knit with Parameters' option, I can see the selection for exp parameter, but it does not save the output HTML filename according to the input value. It saves with the default value (exp_draft.html).
How can I change the output filename according the user selection? Is it something related with Shiny's reactive expression that I should write in the knit's parameter? If yes, then how should I put reactive experession in YAML?
Thanks.
I try to generate multiple reports (1 per group) with rmarkdown::render(), but it produces no section numbers.
I use the following file-structure for this in case you want to reproduce the sample (I tried to simplify each file and use only necessary code to reproduce the error):
*) groups.R: defines groups and subgroups in a nested list (all groups stored in a list and each group is a list itself)
groups <- list(
list(c("subgroup1","subgroup2"),"maingroup1"),
list(c("subgroup3","subgroup4"),"maingroup2")
)
*) main.Rmd: template for the reports
---
output:
pdf_document:
number_sections: true
classoption: a4paper
geometry: left=2cm,right=1cm,top=1.5cm,bottom=1cm,includeheadfoot
fontfamily: helvet
fontsize: 11pt
lang: en
header-includes:
- \usepackage{lastpage}
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \fancyhf{}
- \fancyhead[R]{\fontsize{9}{11} \selectfont \leftmark}
- \fancyhead[L]{\fontsize{9}{11} \selectfont Special report xxx}
- \fancyfoot[R]{\fontsize{9}{0} \selectfont Page \thepage\ of
\pageref{LastPage}}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo =
FALSE,comment=NA,warning=FALSE,message=FALSE)
```
\thispagestyle{empty}
\tableofcontents
\newpage
\setcounter{page}{1}
# Introduction
Some text...
```{r results="asis"}
source("graphics.R")
```
*) graphics.R: generates graphics for each subgroup (sections/section numbers are produced with cat() for each subgroup)
load("actgroup.RData")
source("template_graphics.R")
for (g in 1:length(act.group[[1]][[1]])) {
subgroup.name <- act.group[[1]][[1]][g]
cat("\\clearpage")
cat("\n# ",subgroup.name, "\n")
template_graphics(cars)
cat("\n\n")
cat("\\clearpage")
template_graphics(iris)
cat("\n\n")
cat("\\clearpage")
template_graphics(airquality)
cat("\n\n")
cat("\\clearpage")
cat("\n")
}
*) template_graphics.R: template for plotting
template_graphics <- function(data) {
plot(data)
}
*) loop.R: used for generating all reports as PDF - 1 per group
setwd("YOUR DIRECTORY HERE")
library(rmarkdown)
source("groups.R")
for(i in 1:length(groups)) {
act.group = list(groups[[i]])
save(act.group,file="actgroup.RData")
rmarkdown::render("main.Rmd",
output_format=pdf_document(),
output_file=paste0("Special Report ",act.group[[1]][[2]],".pdf"),
output_dir="~/Reports")
}
The problem is, that the final documents do not show the section numbers. When I knit manually in main.Rmd (pressing knit-Button), the section numbers are printed.
Version rmarkdown::render
Version knit-Button
I thought that pressing the knit-Button also starts the rendering-process with rmarkdown::render()? So it's surprising that the reports are not identical?
In advance I installed tinytex::install_tinytex(). The used latex-packages in main.Rmd were automatically installed during the first time rendering.
I am not sure what the problem is. I use R 4.1.0 and RStudio 2022.02.2.
Thanks for your help!!
The behaviour of pdf_document() as the output-format in rmarkdown::render caused the missing section-numbers.
In my YAML-header in main.Rmd I chose to keep the section numbers with number_sections: true. If this should also be rendered when using rmarkdown::render, it has to be an argument in the function:
pdf_document(number_sections=TRUE)
The code of loop.R produces now pdfs with section numbers:
library(rmarkdown)
source("groups.R")
for(i in 1:length(groups)) {
act.group = list(groups[[i]])
save(act.group,file="actgroup.RData")
rmarkdown::render("main.Rmd",
output_format=pdf_document(number_sections=TRUE),
output_file=paste0("Special Report ",act.group[[1]][[2]],".pdf"),
output_dir="~/Reports")
}
More information on pdf_document() can be found here:
https://pkgs.rstudio.com/rmarkdown/reference/pdf_document.html
Alternatively, fill in just a text-reference as output-format: output_format="pdf_document". When set like this, the options of the YAML-Header are not overwritten and the numbers are also included.
I think that you can pass variables to a YAML element, something like
---
output: html_document
params:
set_title: "My Title!"
title: "`r params$set_title`"
---
(as suggested here). This, however, works for output: html_document but not for bookdown::word_document2. Also, I would like to change the template of my bookdown::word_document2 output, depending on a switch, which I can set in the YAML itself, something like
---
title: ""
params:
include_signature: false
include_footer: true
file: !r if(params$include_footer){system.file("assets/template_footer.docx")}else{system.file("assets/template.docx")}
output:
bookdown::word_document2:
reference_docx: "`r params$file`"
number_sections: false
---
This, however, fails with the error message
Error in yaml::yaml.load(..., eval.expr = TRUE) :
Parser error: while parsing a block mapping at line 8, column 5 did not find expected key at line 8, column 61
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
In addition: Warning message:
In yaml::yaml.load(yaml, handlers = knit_params_handlers(evaluate = evaluate), :
an error occurred when handling type 'r'; using default handler
Execution halted
I have tried other possible versions, eg
params:
include_footer: true
output:
bookdown::word_document2:
reference_docx: !expr ifelse(params$include_footer,system.file("assets/template_footer.docx"),system.file("assets/template.docx"))
(or even other variations, where !expr is replaced by r or !r but nothing seems to have made a difference.
Am I missing something obvious (eg that this is only possible in html_document output), or is this particular trick impossible?
Thanks
Gianluca
I have an XML file (SOME.XML), the contents of which I would like to embed in an .RMD document.
If I was content with having the XML reside directly within the .RMD, I'm aware that I could simply do:
```xml
---some xml here---
```
My embarassing attempts so far are:
```{xml code=readr::read_file('SOME.XML')}
```
...which failed as there is no XML engine.
I have also tried:
````{r results='asis'}
cat('```xml')
cat(readr::read_file('SOME.XML'))
cat('```')
````
...for which, although the knitting completes, the output is not at all correct.
Is this possible? (No doubt there is some trick here that I am missing!)
If needed, I could have a pre-knit stage where the content of the XML file is substituted in before subsequently passing a modified version of the .RMD to rmarkdown::render. However, I'd like to avoid this if possible.
Update:
Using readLines as proposed by the answer is complaining about ...incomplete final line found on 'SOME.XML'. Using readr::read_file() avoids this for me. For my particular project, I am now using:
```xml
`r readr::read_file("SOME.XML")`
```
Thank you to #user2554330 for the elegant solution!
Here's one way to do it:
```xml
`r paste(readLines("SOME.XML"), collapse = "\n")`
```
The idea is to put the XML into inline R code. I think knitr ignores the chunk wrappers because they aren't in the {xml ... format it looks for, but it will see the inline code and expand it. Then Pandoc will handle the formatting.
Here's how to modify your approach to get it to work:
````{r results='asis', echo = FALSE}
cat('```xml\n')
cat(readr::read_file('SOME.XML'), sep = "\n")
cat('\n```\n')
````
new to Stackoverflow, and relatively new to writing documents in RMarkdown. I have most other things down, however, I cannot generate citations and the bibliography in RMarkdown. For the example code below, I have used the \cite{REFNAME} as well as [#REFNAME] syntax. The [#REFNAME] will not even let the document be generated, the \cite{} generates the document but the citation is [?] and the reference is not after the #References section.
I have looked through this site and I cannot get suggested fixes to work. I am hoping that the error I am showing after the code sections will tell someone what the error really is.
---
title: "Title for my document"
date: "`r format(Sys.Date(), '%d %B, %Y')`"
output:
pdf_document:
fig_caption: yes
keep_tex: true
number_sections: true
geometry: margin=0.5in
header-includes: \usepackage{float}
urlcolor: blue
bibliography: bibliography_file.bib
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::knit_hooks$set(mysize = function(before, options, envir) {
if (before)
return(options$size)
})
```
text written \cite{neil_increasing_2008} more text written
# References
My .bib file entry looks like this
#article{neil_increasing_2008,
title = {Increasing incidence of legionellosis in the {United} {States},
1990-2005: changing epidemiologic trends.},
volume = {47},
journal = {Clinical Infectious Diseases},
author = {Neil, K. and Berkelman, R.},
year = {2008},
pages = {591--599}
}
The error is:
Warning message: LaTeX Warning(s): Citation `neil_increasing_2008'
on page 1 undefined on input lin There were undefined references.
If I use the [#neil_increasing_2008] as opposed to the \cite{} then the following error is generate, and it does not generate the document either
pandoc-citeproc: Cannot decode byte '\x87':
Data.Text.Internal.Encoding.Fusion.streamUtf8: Invalid UTF-8 stream
pandoc.exe: Error running filter pandoc-citeproc Filter returned error
status 1 Error: pandoc document conversion failed with error 83
Execution halted