21

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?

  • 5
    Can I just make a comment that would have saved me a couple of hours of frustration with bookdown. Including the \newcommand statements in preamble.tex will produce PDF files as expected, but the html version will not pick up the newcommand (the macros will appear in red), although this didn't generate any errors for me. If you include the \newcommand in 01-foo.Rmd, on the other hand, then both versions will incorporate the new commands. – robin hankin Jul 22 '18 at 20:52
  • @robinhankin you should put any new commands you use in single or double $. See my answer – qwr Jan 23 '19 at 08:19
  • I can partly confirm what Robin said. `preamble.tex` is not respected when converting to `.html` via `bookdown::render_book()`. Putting the code (only) in the first `.Rmd` will work for `.html` (note the requirement that chapters must start with `#`), but then fails to output to `.pdf` via `bookdown::render_book(, output_format = "pdf_document")`. I guess `preamble.tex` would then work. All this tells me is that it's better to stick with HTML in my case (all I wanted was an easy way to colorize text and doing that with LaTeX seemed to be the easiest approach). – Marius Hofert May 05 '19 at 14:08

4 Answers4

16

Use \newcommand{\var}{\mathrm{Var}} exactly like you would in LaTeX:

enter image description here

---
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 $...$.

Werner
  • 14,324
  • 7
  • 55
  • 77
  • Or, just wrap that definition in `\ensuremath{ ... }` – user101089 Jan 16 '17 at 02:55
  • 1
    [`\operatorname` handles spacing better than `\mathrm`](https://tex.stackexchange.com/a/48463/116513) – qwr Sep 07 '18 at 04:20
  • @qwr: Not necessarily here. – Werner Sep 07 '18 at 04:41
  • Is it possible to put `\newcommand{\var}{\mathrm{Var}}` in a `header.html`? – YulongNiu Jul 08 '19 at 13:40
  • @YulongNiu: Not that I'm aware of. You'll have to ensure that it forms part of valid LaTeX syntax. It should be able to form part of the `header-includes` clause. As in, `header-includes: - \usepackage{something} - \newcommand{\var}{\mathrm{Var}} - \...` – Werner Jul 08 '19 at 16:40
8

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**.
lowndrul
  • 3,715
  • 7
  • 36
  • 54
  • 2
    @Iowndrul: Thank you for providing an option for bookdown both for PDF & HTML! For me, it works well for math elements like `\newcommand{\var}{\mathrm{Var}} `. However, for some reason it does not work for plain text, i.e. if I want to create a shortcut for a long word, like `\newcommand{\short}{AreallylongwordIhavetotypefrequently}`. Would you know of any solution? I would strongly prefer \short to `r short` as proposed here https://stackoverflow.com/questions/52438607/how-can-i-use-latex-newcommand-in-rmd?noredirect=1&lq=1 – mavericks Feb 07 '20 at 09:37
6

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*}
$$
qwr
  • 9,525
  • 5
  • 58
  • 102
1

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.