I am trying to use Rmarkdown to create answer/solutions twin PDF documents. I embedded the solutions in a frame using the tcolorbox LaTeX package. Also, I am using LaTeX's comment package to easily toggle the solutions on and off. However, R chunks inside the comment environment are not well rendered. Here's a MWE:
---
title: "Untitled"
output:
pdf_document
header-includes:
- \usepackage{tcolorbox}
- \usepackage{comment}
- \includecomment{comment} % toggle include / exclude
- \newcommand{\benum}{\begin{enumerate}}
- \newcommand{\eenum}{\end{enumerate}}
---
```{r, include=FALSE}
library(tidyverse)
```
\benum
\item The R chunk inside the \verb+comment+ environment is not rendered correctly:
\begin{comment}
\tcolorbo
```{r, echo=TRUE, eval = TRUE, results='asis'}
a <- rnorm(20)
a
```
\endtcolorbox
\end{comment}
\item But the same chunk outside the \verb+comment+ environment is rendered fine:
\tcolorbox
```{r, echo=TRUE, eval = TRUE, results='asis'}
a <- rnorm(20)
a
```
\endtcolorbox
\eenum
Here's the result:
How can I achieve what I want?
Many thanks in advance!
Related
I use Rmarkdown to write python code and knit to pdf file for some reason...
I want to use and display greek characters like lambda in my code.
e.g.
def function(X,Y,λ,h):
# do stuff
return w
With default engine, it shows error message as below:
! LaTeX Error: Unicode character λ (U+03BB)
not set up for use with LaTeX.
Error: LaTeX failed to compile report.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See report.log for more info.
Execution halted
If I change the latex engine to xelatex or lualatex, it can knit to a pdf but the greek character disappear. Like this:
def function(X,Y, ,h):
# do stuff
return w
Do folks have any idea how to address that? Really appreciate it if someone could help.
Edited: add a minimal reproducible example as asked by the comment.
---
title: "Minimal reproducible example"
date: "2022-11-08"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{python}
def function(X,Y,λ,h):
# do stuff
return w
```
You'll need to choose a font which does have Greek letters. For example with Arial (using Arial here because many people have it installed, choose a nicer looking font if you have it):
---
title: "Minimal reproducible example"
date: "2022-11-08"
output:
pdf_document:
latex_engine: xelatex
keep_tex: true
header-includes:
- \setmonofont{Arial}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{python}
def function(X,Y,λ,h):
# do stuff
return w
```
I am creating pdf slides using rmarkdown and beamer. When using latex instead of rmarkdown, I can include arbitrary pages from pdf files into my slides with
\usepackage{pdfpages}
...
\includepdf[pages={1-10}]{another_file.pdf}
Is it possible to achieve this with rmarkdown? Note that when just issuing the \includepdf command, intended to be located between slides, pandoc wraps it between \begin{frame} and \end{frame}.
Not a perfect solution but it works (adapted from https://tex.stackexchange.com/questions/11458/error-when-inserting-a-pdf-page-into-a-beamer-presentation?newreg=10fd6a4a46c642118eb4ec905cf87303): use \includegraphics instead of includepdf. This works inside of frames but you have to manyally create a frame for each page you want to insert as it only allows to insert a single page at time.
---
title: "Foo"
output:
beamer_presentation:
---
# Stolen image
---
\includegraphics[page=1,width=\paperwidth]{lecture-1-terminal.pdf}
# My own work
## My slide 1
Great stuff!
In rmarkdown you can use pdfpages like this:
---
output:
beamer_presentation:
keep_tex: true
header-includes:
- \usepackage{pdfpages}
- \setbeamercolor{background canvas}{bg=}
- \makeatletter\beamer#ignorenonframefalse\makeatother
---
test
``` {=latex}
\end{frame}
\includepdf[pages=1-10]{example-image-duck}
\begin{frame}
```
test
(the line \setbeamercolor{background canvas}{bg=} is necessary for beamer versions < 3.64, a patch has been added in 9e3bb9)
As you mentioned, you can inlcude raw TeX in Pandoc Markdown. For me the following works:
$ pandoc -t beamer
foo
\includepdf[pages={1-10}]{another_file.pdf}
bar
^D
which results in:
\begin{frame}
foo
\includepdf[pages={1-10}]{another_file.pdf}
bar
\end{frame}
Maybe you need to update your pandoc version? (I'm currenlty using 2.0 from pandoc nightlies)
Does R Markdown have a similar construct to LaTex's "newcommand"? I would like to be able to define things like \var to be \mathrm{Var} to avoid the extra typing in math mode. If not, what do people do to reduce repetition in typesetting equations in markdown?
Use \newcommand{\var}{\mathrm{Var}} exactly like you would in LaTeX:
---
title: "Untitled"
author: "An Author"
date: "January 15, 2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newcommand{\var}{\mathrm{Var}}
## R Markdown
This is an R Markdown document. $\var+2$ Markdown is a simple formatting syntax for
authoring HTML, PDF, and MS Word documents. For more details on using R Markdown
see <http://rmarkdown.rstudio.com>.
Note that in order for it to be processed correctly in the output, you'll have to use $...$.
I'm using bookdown and need to have something that works consistently across pdf, html, and docx output. None of the above solutions worked for my case. Here is the hack I settled on:
preamble.tex
\usepackage{amsthm}
\DeclareMathOperator*{\argmin}{argmin}
\newcommand{\var}{\mathrm{Var}}
YAML Header:
---
title: "A Minimal Book Example"
author: "Yihui Xie"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
output:
bookdown::pdf_book:
includes:
in_header: preamble.tex
toc: no
bookdown::word_document2:
reference_docx: template.docx
bookdown::gitbook:
split_by: none
documentclass: article
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
---
<!--- For HTML Only --->
`r if (!knitr:::is_latex_output()) '
$\\DeclareMathOperator*{\\argmin}{argmin}$
$\\newcommand{\\var}{\\mathrm{Var}}$
'`
<!--- For DOCX Only --->
`r if (!knitr:::is_latex_output() & !knitr:::is_html_output()) '
\\DeclareMathOperator*{\\argmin}{argmin}
\\newcommand{\\var}{\\mathrm{Var}}
'`
# Prerequisites
This is a _sample_ book written in **Markdown**.
To get around the requirement of \DeclareMathOperator needing to be in the preamble, use \operatorname:
\newcommand{\Var}{\operatorname{Var}}
$\Var(X)$
(\operatorname handles spacing better than \mathrm)
To use \newcommand properly in HTML output, your LaTeX should be in-line with single $ or in double $$. This applies to environments like \begin{align*} too.
---
title: "Test"
author: "qwr"
date: "January 22, 2019"
output: html_document
---
\newcommand{\Var}{\operatorname{Var}}
$\Var(X)$
$$
\begin{align*}
\Var[Y] &= x \\
&= 3
\end{align*}
$$
I had issues with the above solution when outputting as a beamer presentation, particularly when using the equation mode ($$.$$ rather than $.$). Putting the new commands in a separate file fixed the issue for me.
---
title: Title
author: Author
date: "8/22/2018"
output:
beamer_presentation:
includes:
in_header: preamble.tex
---
Where preamble.tex contains your user defined command(s)
\newcommand{\var}{\mathrm{Var}}
Then you can use the command both inline ($\var$) and in equation mode ($$\var$$)
You can also put other stuff in preamble.tex like frame numbering, etc.
Below is an rmarkdown document with a LaTex equation. The default for these equations is centre. How do I left-align this equation? I have searched the similar answers but none of the suggestions work on this simple problem.
---
title: "Untitled"
author: "Llew Mills"
date: "1 May 2016"
output: pdf_document
---
## R Markdown
\begingroup\Large
\begin{equation*}
\Delta PsuedoR^2_{\zeta_{0}} = \frac {0.488 - 0.624}{0.488} = -0.219
\end{equation*}
\endgroup
This latex solution on tex.SE gives an answer that we can adapt to knitr. To have all equation of the document aligned on the left, you can use classoption fleqn and write equation in regular pandoc latex-math style (surrounded with $$):
---
classoption: fleqn
header-includes:
- \setlength{\mathindent}{0pt}
---
$$\Delta PsuedoR^2_{\zeta_{0}} = \frac {0.488 - 0.624}{0.488} = -0.219$$
Note that you don't have to add \usepackage{amsmath} because the default latex template already includes it.
I'm building a presentation using rmarkdown and LaTeX/Beamer. I would like to reduce the spacing between the displayed R-commands and R-output. I believe this is related to the paragraph spacing options in LaTeX/Beamer.
Is this something I should do in rmarkdown (chunk options, knit_hooks, or something else?), in the pandoc Yaml header (some pandoc option?), or in the LaTeX beamer template file? I feel like it should be in the LaTeX template file.
Below is a working example of a minimal markdown file, and a .tex template file I'm using to control some beamer settings.
example.Rmd
---
title: "Untitled"
author: "Ryan"
date: "March 1, 2016"
output:
beamer_presentation:
pandoc_args: '--latex-engine=xelatex'
includes:
in_header: latex-topmatter.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Vertical Spacing is too much
Here is a working example.
- some
- bullets
Example code:
```{r, echo = TRUE}
a <- 1
a
a+a
```
latex-topmatter.tex
% declare overall beamer theme to use as baseline
\usetheme{default}
% make code-output smaller
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\tiny,commandchars=\\\{\}}
% make console-output smaller:
\makeatletter
\def\verbatim{\tiny\#verbatim \frenchspacing\#vobeyspaces \#xverbatim}
\makeatother
% set vertical spacing between paragraphs:
% \parskip{0pt}
% \addtobeamertemplate{blocks}{}{\setlength{\parskip}{0pt}}
% \addtobeamertemplate{block begin}{}{\setlength{\parskip}{0pt}}
% \addtobeamertemplate{block end}{}{\setlength{\parskip}{0pt}}
% % \setlength{\emergencystretch}{0em}
\setlength{\parskip}{0pt}
I've tried making the font of the R-commands or R-output smaller, which does not seem to affect the paragraph spacing.
I've tried using knit_hooks() as in this example:
https://github.com/ramnathv/slidify/issues/189, which mostly works - but then i can't seem to reduce the fontsize of the code and output.
I've also tried using \parskip{0pt}, and several other beamer options or parskip options, which are commented in the above latex-topmatter.tex section. None of them seem to change the spacing between chunks of text, R-code, or R-output. Am I even looking in the right place?
Here is a working example. Notice the definitions at the end of the header file:
Source code chunks are contained inside a Shaded environment which in turn uses \OuterFrameSep for its spacing. So we need to redefine that.
With \preto we prepend the commands \topsep=-10pt \partopsep=-10pt to every verbatim environment. This affects the spacing of output chunks.
example.Rmd
---
title: "Untitled"
author: "Martin"
date: "January 4, 2017"
output:
beamer_presentation:
keep_tex: yes
pandoc_args: --latex-engine=xelatex
includes:
in_header: latex-topmatter.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Vertical Spacing is just right
Here is a working example.
- some
- bullets
Example code:
```{r, echo = TRUE}
a <- 1
a
a+a
```
latex_topmatter.tex
% declare overall beamer theme to use as baseline
\usetheme{default}
% make code-output smaller
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\tiny,commandchars=\\\{\}}
% make console-output smaller:
\makeatletter
\def\verbatim{\tiny\#verbatim \frenchspacing\#vobeyspaces \#xverbatim}
\makeatother
\setlength{\parskip}{0pt}
\setlength{\OuterFrameSep}{-4pt}
\makeatletter
\preto{\#verbatim}{\topsep=-10pt \partopsep=-10pt }
\makeatother