RMarkdown not rendering Stan code chunk as code - r-markdown

When I knit the following RMarkdown document:
title: "Reprex"
author: "Jeremy Colman"
date: "17/07/2018"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{stan, output.var='priors', eval = FALSE, tidy = FALSE}
parameters {
real<lower = 0> qtilde1;
}
model {
qtilde1 ~ gamma(38.9, 0.67);
}
```
The Stan code chunk is rendered as ordinary text, including the three reverse single quotes and word stan from the chunk header. I cannot show that in this post because stackoverflow tells me, correctly but unhelpfully, "Your post appears to contain code that is not properly formatted as code". That sums up my problem!
Code chunks in R are rendered correctly.

Your
```{stan output.var='priors', eval = FALSE, tidy = FALSE}
needs to be flush-left, but you have a leading space before the ```

Related

Difference in PDFs when manually generated with Knit-Button vs rmarkdown::render() - e.g. section numbers not always included

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.

How to have a setup chunk both in the parent and a child document?

I usually split my r-markdown document into master.rmd and several child.rmd documents. I first work on each child.rmd document as a standalone document. While at it, it is convenient to have a setup chunk in child.rmd so that RStudio knows to run it before any other chunk. The problem arises when I then include child.rmd into master.rmd which also has a setup chunk.
Is there a way to have setup chunks both in the parent and the child documents?
My documents usually look something like this:
master.rmd:
---
title: "master"
output: html_document
params:
standalone: no
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
child.rmd:
---
title: "child"
output:
html_document:
df_print: paged
params:
standalone: yes
---
```{r setup, include=FALSE, eval=params$standalone}
library(stats)
```
```{r}
if (params$standalone) {
plot(cars)
} else {
plot(iris)
}
```
What does the standalone: YAML setting do?
When messing with your code, I encounter an error that your child and master had the same chunk names ("setup"). So to help R, make your R chunks unique names.
Here is what I did, to run the master.Rmd and have it generate what is in child.Rmd. I tried to make the code more simple for myself to be able to try and see if I can help. Please let me know if this helps you decipher your Rmarkdown issue. These files are in the exact same directory
master.rmd
---
title: "master"
output: html_document
---
```{r setup, include=FALSE, child='child.Rmd'}
knitr::opts_chunk$set(echo = TRUE)
```
child.rmd
---
title: "child"
output:
html_document:
df_print: paged
---
```{r setup1, include=TRUE}
library(stats)
if (TRUE) {
plot(cars)
} else {
plot(iris)
}
```
Below is the output I get when I run the master.rmd file

Citations not generating in RMarkdown

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

How to insert a reference in a table caption in a bookdown document that works for both pdf and html output

I use bookdown to generate a document in both html and pdf. How could I insert a reference to a section of the document in the caption of a table?
Using \\ref{sec:FirstSection} works fine with pdf_book (but not gitbook):
---
title: "Test"
output: bookdown::pdf_book
---
# A section {#sec:FirstSection}
The dataset in Table \#ref(tab:aTable) contains some data.
# Another section
```{r, aTable, echo = FALSE}
knitr::kable(
cars[1:5, ],
caption = "See Section \\ref{sec:FirstSection}."
)
```
whilst using \\#ref(sec:FirstSection) works fine with gitbook (but not pdf_book)
---
title: "Test"
output: bookdown::gitbook
---
# A section {#sec:FirstSection}
The dataset in Table \#ref(tab:aTable) contains some data.
# Another section
```{r, aTable, echo = FALSE}
knitr::kable(
cars[1:5, ],
caption = "See Section \\#ref(sec:FirstSection)."
)
```
You can use text references, a Markdown extension provided by bookdown.
---
title: "Test"
output: bookdown::gitbook
---
# A section {#sec:FirstSection}
The dataset in Table \#ref(tab:aTable) contains some data.
# Another section
(ref:aTable-caption) See Section \#ref(sec:FirstSection).
```{r, aTable, echo = FALSE}
knitr::kable(
cars[1:5, ],
caption = "(ref:aTable-caption)"
)
```
This works for both pdf and html but there might be an easier way.
---
title: "Test"
output: bookdown::gitbook
---
# A section {#sec:FirstSection}
The dataset in Table \#ref(tab:aTable) contains some data.
# Another section
```{r, aTable, echo = FALSE}
txt <- ifelse(knitr:::is_latex_output(), "\\ref{sec:FirstSection}",
"\\#ref(sec:FirstSection)")
knitr::kable(
cars[1:5, ],
caption = paste0("See Section ", txt, ".")
)
```

break a slide of reveal.js (xaringan) when it's long

I'm actually using xaringan, but it uses reveal.js, so it should be the same.
I have a slide which prints bibliography using RefManageR, and I'd like to use as many slides as needed:
---
```
{r results = "asis", echo = FALSE}
PrintBibliography(bib, .opts = list(check.entries = FALSE, sorting = "ynt"))
```
---
I guess I'm looking for some type of allowframebreaks, but I couldn't manage to find one.
Xaringan uses remark.js, not reveal.