R 帮助手册中可以包含乳胶数学吗?

Can R help manuals have latex math in them?

我正在开发一个 R 包,我正在使用包 Roxygen2 为我的 R 函数编写帮助手册。我想知道的是,是否可以在手册页中将乳胶用于数学方程式?

例如,如果我有一个名为 add2 的函数,它执行以下操作:

add2 = function(x,y){
       z = x+y
       return(z)
}

使用 Roxygen2 文档我得到了以下信息:

##' @include add2.R
{}

##' Compute the sum of x_1 and x_2
##'
##' Computes the sum of x_1 and x_2
##'
##' @param x_1 number of guys
##' @param x_2 number of girls
##' @return The sum of the two values x_1 and x_2
##'
##' @example examples/adding.R
##' @export
##' @author Name

这对我有用,但这在帮助手册中将 x1 和 x2 显示为 x_1 和 x_2,而我希望它看起来像乳胶数学并且实际上有下标x,即乳胶中的 $x_1$ 和 $x_2$。

有什么办法可以做到这一点,或者 R 不适应这个吗?

有点。如果您想在纯文本输出中使用 LaTeX 标记的(未处理的)版本,请使用类似 \eqn{x_1} 的内容(或者您可以说类似 \eqn{x_1}{x1} 的内容)。 "sort of" 部分是我不确定 LaTeX 处理将完成哪些特定输出格式——例如,我猜你会看到 HTML 格式的输出版本在(例如)RStudio 文档窗格中 不会 尊重此标记。 (LaTeX 标记肯定 用于手册的 PDF 版本,我几乎从不看...)

我要继续引用 Mathematics section of Writing R Extensions ...

Mathematical formulae should be set beautifully for printed documentation yet we still want something useful for text and HTML online help. To this end, the two commands \eqn{latex}{ascii} and \deqn{latex}{ascii} are used. Whereas \eqn is used for “inline” formulae (corresponding to TeX’s $…$), \deqn gives “displayed equations” (as in LaTeX’s displaymath environment, or TeX’s $$…$$). Both arguments are treated as ‘verbatim’ text.

Both commands can also be used as \eqn{latexascii} (only one argument) which then is used for both latex and ascii. No whitespace is allowed between command and the first argument, nor between the first and second arguments.

The following example is from Poisson.Rd:

\deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%

p(x) = \lambda^x exp(-\lambda)/x!} for \eqn{x = 0, 1, 2, \ldots}.


截至 2020 年 5 月 8 日,Wolfgang Viechtbauer 的 mathjaxr package 在 CRAN 上。它

Provides 'MathJax' and macros to enable its use within Rd files for rendering equations in the HTML help files.

来自README file:

[After installing the package, editing the package DESCRIPTION file appropriately, and adding \loadmathjax{} to the Rd file ... a]n inline equation can then be added with the \mjeqn{latex}{ascii} macro, with the LaTeX commands for the equation given between the first set of curly brackets (which will be rendered in the HTML and PDF help pages) and the plain-text version of the equation given between the second set of curly brackets (which will be shown in the plain text help). With the \mjdeqn{latex}{ascii} macro, one can add ‘displayed equations’ (as in LaTeX’s displaymath environment).

哈德利·威克姆 (Hadley Wickham) 引用 O'Reilly 的 "R Packages":

You can use standard LaTeX math (with no extensions). Choose between either inline or block display:

  • \eqn{a + b}: Inline equation
  • \deqn{a + b}: Display (block) equation

所以,使用\eqn\deqn是官方推荐的方式。