R Markdown document crops code snippets in PDF output - r

The following header is from a R Markdown document which I have compiled as a PDF. It results in code snippets being cropped. Commenting out the PDF output block and uncommenting the HTML block results in well-formatted HTML output.
Is there a parameter I can change to fix this? Or do I need to format my code snippets differently?
---
title: "fmodbc Package"
author: "Bobby Rohrkemper, Software Developer at Schweiz Tourismus"
date: "`r Sys.Date()`"
# output:
# rmarkdown::html_vignette:
# toc: TRUE
output:
pdf_document:
toc: TRUE
vignette: >
%\VignetteIndexEntry{Vignette Title}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
Or should I perhaps try a different theme? I would be interested in the Tufte Handout theme, but thought it makes more sense to fix the standard output first.
http://rmarkdown.rstudio.com/tufte_handout_format.html
PDF output is cropped:
HTML output looks good:
Code snippet:
This produces the results above. I am not modifying it in the PDF and HTML versions.
```{r}
# names(dat)
# "__Backups" "__Budget" "__Comments" "__Documents" "__globals" "__KPI" "__Marketing Activities" "__MarketManager" "__Segmentation" "__sts_Account" "__sts_Budget" "__sts_Mandate" "__sts_ProfitCenter" "__UserLog" "__VL_PlanningStatus"
```

Use the chunk option tidy = TRUE.
tidy: (FALSE; logical) whether R code should be tidied up using the function tidy_source() in the formatR package; if it failed to tidy up, original R code will not be changed; tidy=TRUE is like keep.source=FALSE in Sweave, but it also tries not to discard R comments (N.B. this option does not work in certain cases; see http://yihui.name/formatR for more information)
---
title: "fmodbc Package"
author: "Bobby Rohrkemper, Software Developer at Schweiz Tourismus"
date: "`r Sys.Date()`"
# output:
# rmarkdown::html_vignette:
# toc: TRUE
output:
pdf_document:
toc: TRUE
vignette: >
%\VignetteIndexEntry{Vignette Title}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r}
library(knitr)
opts_chunk$set(tidy = TRUE)
```
```{r}
# names(dat)
# "__Backups" "__Budget" "__Comments" "__Documents" "__globals" "__KPI" "__Marketing Activities" "__MarketManager" "__Segmentation" "__sts_Account" "__sts_Budget" "__sts_Mandate" "__sts_ProfitCenter" "__UserLog" "__VL_PlanningStatus"
```

Related

RMarkdown: Customize Color and Font Size of (automated) Citations

I am fairly new to RMarkdown and trying to apply some LaTeX logic here. Currently, I am creating a PDF presentation with RMarkdown (beamer_presentation). Is it possible to change the font size and color of automatic citations ([#shortname]) so that e.g., all citations appear slightly smaller than the normal text and in gray?
In LaTeX beamer presentations, I managed to re-define the cite command and apply this. I was not yet able to recreate this in RMarkdown however.
When I was trying to manually (I'd much prefer automatic a solution) change the font color of citations \textcolor{gray}{[e.g., #shortname]} (also $\textcolor{gray}{[e.g., #shortname]}$), I received this error message:
I was unable to find any missing LaTeX packages from the error log slides.log. ! Missing $ inserted. $ l.182 \end{frame} Try to find the following text in slides.Rmd: \end{frame}
You may need to add $ $ around a certain inline R expression r in slides.Rmd (see the above hint). See https://github.com/rstudio/rmarkdown/issues/385 for more info.
The link in the error message did not help me either.
I am grateful for your help! I'll include a MWE below.
Till
---
title: "A title"
author: "Till"
date: 25.07.2022
output:
beamer_presentation:
incremental: true # bullet points on multiple pages
toc: false # add generated page listing sections
slide_level: 2 # depth level for render content
latex_engine: lualatex
keep_tex: TRUE
bibliography: literature.bib
csl: american-sociological-association.csl
header-includes: \usepackage{xcolor}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(tinytex.verbose = TRUE) # for debugging
```
# First Section
## Example Slide
- Some text which will be followed by a citation \textcolor{gray}{[e.g., #shortname]}
- Some more text, now without a citation
The literature.bib file could look somewhat like this:
#article{shortname,
title = {citation title},
journaltitle = {Journal},
shortjournal = {Journal},
author = {Lastname, Firstname},
date = {2022},
}
The problem with your \textcolor approach is that you can't use markdown syntax in the argument of a latex macro. You can avoid this problem by using \begingroup \color{gray} [e.g., #shortname] \endgroup:
---
title: "A title"
author: "Till"
date: 25.07.2022
output:
beamer_presentation:
incremental: true # bullet points on multiple pages
toc: false # add generated page listing sections
slide_level: 2 # depth level for render content
latex_engine: lualatex
keep_tex: TRUE
bibliography: literature.bib
csl: american-sociological-association.csl
header-includes: \usepackage{xcolor}
---
#```{r setup, include=FALSE}
# I did not know how to include R-Chunks in the code block withouth breaking the formatting, so just remove the Hashtags before the three ticks and this endless comment
knitr::opts_chunk$set(echo = TRUE)
options(tinytex.verbose = TRUE) # for debugging
#```
# First Section
## Example Slide
- Some text which will be followed by a citation \begingroup \tiny\color{gray} [e.g., #shortname] \endgroup
- Some more text, now without a citation

Replace file header containing escape characters

I created a vignette for a package with following header:
---
title: "My package vignette"
output: rmarkdown::html_document
vignette: >
%\VignetteIndexEntry{MyPackage}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
However, vignette format doesn't allow full functionalities allowed by html_document.
I would like to automatically change the YAML header in order to have the ability to knit the vignette in full html_document format (with options like toc_float: true)
I'm trying to read the .Rmd file with ReadLines and replace the header using gsub, but I'm struggling with escape characters / regex:
content <- readLines('vignettes/MyPackage.Rmd',encoding = 'UTF-8')
vignette_header <- "output: rmarkdown::html_document
vignette: >
%\\VignetteIndexEntry{MyPackage}
%\\VignetteEngine{knitr::rmarkdown}
%\\VignetteEncoding{UTF-8}"
normal_header <-
'output:
html_document:
toc_float: true'
gsub(vignette_header,normal_header,content )
Error in gsub(vignette_header, normal_header, content) :
regular expression 'output: rmarkdown::html_document
vignette: >
%\VignetteIndexEntry{ALPSYSparams}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}' incorrect, because of 'Invalid contents of {}'
Thanks for your suggestions, alternative methods to modify a file header with escape characters welcome.
Instead of modifying header, as a workaround I made two Rmarkdown files with different headers, and used child chunck option to insert the same Markdown body:
Vignette :
---
title: "My package vignette"
output: rmarkdown::html_document
vignette: >
%\VignetteIndexEntry{MyPackage}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r child=here::here('data/MyPackageVignetteBody.Rmd')}
```
Fully featured Markdown :
---
title: "My package fully featured Markdown"
output:
html_document:
toc: true
toc_float: true
---
```{r child=here::here('data/MyPackageVignetteBody.Rmd')}
```

Rmarkdown Beamer presentation, option clash clash for xcolor

I am trying to build a beamer presentation using rmarkdown. In my presentation I want to include tables using the kable, and kableExtra packages. I am having issues with this because one of the LaTex packages that kableExtra requires is already loaded by the beamer presentation with different options. This is the error message that I receive.
! LaTeX Error: Option clash for package xcolor.
I have been searching for a fix for this but have not had any luck. I have found solutions on the LaTex pages, here and here, but I do not know LaTex and I have not figured out how to apply these solutions in the rmarkdown arena. I have tried looking at the Latex templates in rmarkdown, but I do not understand it well enough to try and implement these solutions.
Any thoughts or solutions would be much appreciated. Here is just a quick sample of the .Rmd that gives the error.
---
title: "Untitled"
author: "Author"
date: "April 28, 2018"
output:
beamer_presentation:
keep_tex: true
header-includes:
- \usepackage[table]{xcolor}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:6]
```
## Slide with R Output
```{r cars, echo = TRUE}
kable(dt, format = "latex")
```
## Slide with Plot
```{r pressure}
plot(pressure)
```
The linked answer on the TeX stackexchange suggests adding table to the class options for the document e.g. \documentclass[a4paper,table]{article}. In order to do this in RMarkdown, you can use a classoption: line in your YAML header:
---
title: "Untitled"
author: "Author"
date: "April 28, 2018"
classoption: table
output:
beamer_presentation:
keep_tex: true
---

How to remove compact title from R markdown to latex conversion?

I wrote my own titlepage and it is loaded via an include in the R-markdown file. However, this conflicts with the pandoc title. I am trying to find settings in the R markdown yaml header such that pandoc does not insert the following code snipped into the tex-file.
% Create subtitle command for use in maketitle
\newcommand{\subtitle}[1]{
\posttitle{
\begin{center}\large#1\end{center}
}
}
\setlength{\droptitle}{-2em}
\title{}
\pretitle{\vspace{\droptitle}}
\posttitle{}
\author{}
\preauthor{}\postauthor{}
\date{}
\predate{}\postdate{}
There is no clear indication in the pandoc documents or the r markdown guidelines how to disable the title generation. Any help would be appreciated.
Update: In particular, I am looking for solutions that allow me to keep creating my title page with the \maketitle command. That is why I focussed on this particular code snipped that I want to get rid of.
I also use my own title page with rmarkdown documents for latex/pdf outputs. To remove the title, you can add the following command in a text file called with in_header :
\AtBeginDocument{\let\maketitle\relax}
A reproductible example with the header.tex file built directly within the Rmd document:
---
title: "RMarkdown No title Test"
author: "StatnMap"
date: "July 30, 2017"
output:
pdf_document:
includes:
in_header: header.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r rm_title_page, echo=FALSE}
head <- cat('
\\AtBeginDocument{\\let\\maketitle\\relax}
', file = "header.tex")
```
# Title 1
**Some text**
# Title 2
**Some text**
Using compact-title: false in the YAML works.
---
title: "This title is not compact"
author: "Test"
date: "2019 May 10"
output: pdf_document
compact-title: false
---
I had the same problem today. Here's what I did. (Maybe I'll update the solution when I come up with something better.)
The solution is dumb but useful. I can't set an arbitrary space between the lines now, because I used \newline.
---
title: "\\huge My Smart Title"
author: "\\newline \\Large My Smart Author"
date: "\\newline \\Large 2018-12-25"
output:
pdf_document:
includes:
in_header: preamble.tex
latex_engine: xelatex
---
Below are the outputs before and after the solution.
BEFORE:
AFTER:
Note:
You may be confused about the different sizes of the "author" and the "date" in the two pictures above, if you don't know that the fontsize of the "author" and the "date" is \large instead of \Large by default.
END

Figure name in caption using RMarkdown

I am writing my first .rmd report using RMarkdown and then I knit it to pdf file. As I write it in my national language, I would like to have figures captions in my language too. The problem is that the default caption format is "Figure 1: My caption". I would like to change this generative "Figure 1:" part but I couldn't find how. Any help will be appreciated.
Try specifying the language in the YAML header of an rmarkdown document (documentation link):
---
title: "Crop Analysis Q3 2013"
output: pdf_document
fontsize: 11pt
geometry: margin=1in
lang: german
---
The language code will be processed by the babel LaTeX package (at least in the case of pdflatex).
I found out that it is possible to do using LaTeX:
---
title: "My raport"
output:
pdf_document:
fig_caption: yes
header-includes:
- \usepackage{caption}
---
\def\figurename{MyFigureName}
Still: is there any simpler way?
It should work like this:
---
output:
pdf_document:
fig_caption: true
---
```{r figWithCaption, echo=F, fig.cap="My Figure Caption"}
plot(cars) # your figure
```

Resources