R Markdown 与 LaTex 中的 "newcommand" 类似的功能?

R Markdown similar feature to "newcommand" in LaTex?

R Markdown 是否具有与 LaTex 的 "newcommand" 相似的结构?我希望能够将 \var 之类的东西定义为 \mathrm{Var} 以避免在数学模式下进行额外的输入。如果不是,人们如何减少 markdown 中排版方程式的重复?

使用 \newcommand{\var}{\mathrm{Var}} 就像在 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>.

请注意,为了在输出中正确处理它,您必须使用 $...$.

为了绕过 \DeclareMathOperator 需要在序言中的要求,use \operatorname:

\newcommand{\Var}{\operatorname{Var}}

$\Var(X)$

(\operatorname handles spacing better than \mathrm)

要在 HTML 输出中正确使用 \newcommand,您的 LaTeX 应该与单 $ 或双 $$ 一致。这也适用于 \begin{align*} 等环境。

---
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*}
$$

在输出为 beamer 演示文稿时,我遇到了上述解决方案的问题,特别是在使用方程模式($$.$$ 而不是 $.$ 时)。将新命令放在单独的文件中为我解决了这个问题。

---
title: Title
author: Author
date: "8/22/2018"
output:
  beamer_presentation:
    includes:
      in_header: preamble.tex
---

其中 preamble.tex 包含您的用户定义命令

\newcommand{\var}{\mathrm{Var}}

然后你可以在行内($\var$)和方程模式($$\var$$)中使用命令

您还可以将其他内容放入 preamble.tex,例如帧编号等

我正在使用 bookdown,需要在 pdf、html 和 docx 输出中保持一致。 None 以上解决方案适用于我的案例。这是我确定的技巧:

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