rdevtoolsroxygen2

R help pages with multiline LaTeX equations


I am writing R package documentation with roxygen2. I want to insert the following multiline equation into a help page, but my LaTeX code is not being rendered.

enter image description here

#' hello2
#'
#' @description
#' \deqn{
#' F(t)= \begin{cases}\alpha(t) f_{L}(t)+[1-\alpha(t)] f_{C}(t) & t_{L}<t<t_{C} \\ \beta(t) f_{C}(t)+[1-\beta(t)] f_{R}(t) & t_{C}<t<t_{R}\end{cases}
#' }
#' 
#' @export
hello2 <- function() {}

enter image description here


Solution

  • New answer

    Support for KaTeX in HTML rendering of Rd files was added in R 4.2.0. Support for amsmath in PDF rendering of Rd files was added in R 4.2.2. Hence packages with Depends: R (>= 4.3) can safely specify multiline equations using \deqn. No need for mathjaxr.


    Original answer

    Just to demonstrate that it's possible once you've integrated mathjaxr correctly:

    tmp <- tempfile()
    dir.create(tmp)
    cwd <- setwd(tmp)
    
    pkgname <- "foo"
    usethis::create_package(pkgname, rstudio = FALSE, open = FALSE,
                            fields = list(Imports = "mathjaxr", RdMacros = "mathjaxr"))
    setwd(pkgname)
    text <- "#' A title
    #' 
    #' \\loadmathjax{}
    #' A description.
    #' 
    #' @param a,b Arguments.
    #' 
    #' @details
    #' An irrelevant equation:
    #' \\mjtdeqn{F(t) = \\left\\lbrace\\begin{array}{ll} \\alpha(t) f_{L}(t) + \\lbrack 1 - \\alpha(t) \\rbrack f_{C}(t)\\,, & t_{L} < t < t_{C}\\,, \\cr \\beta(t) f_{C}(t) + \\lbrack 1 - \\beta(t) \\rbrack f_{R}(t)\\,, & t_{C} < t < t_{R}\\,. \\end{array}\\right.}{%
    #'           F(t) = \\begin{cases} \\alpha(t) f_{L}(t) + \\lbrack 1 - \\alpha(t) \\rbrack f_{C}(t)\\,, & t_{L} < t < t_{C}\\,, \\cr \\beta(t) f_{C}(t) + \\lbrack 1 - \\beta(t) \\rbrack f_{R}(t)\\,, & t_{C} < t < t_{R}\\,. \\end{cases}}{%
    #'           ... a plain text translation ...}
    #' 
    #' @noMd
    #' @export
    #' @importFrom mathjaxr preview_rd
    add <- function(a, b) a + b
    "
    cat(text, file = file.path("R", "add.R"))
    roxygen2::roxygenize(".")
    

    PDF output

    mathjaxr::preview_rd("add.Rd", type = "pdf")
    

    enter image description here

    HTML output

    mathjaxr::preview_rd("add.Rd", type = "html")
    

    enter image description here

    Plain text output

    mathjaxr::preview_rd("add.Rd", type = "txt")
    

    enter image description here

    A few remarks

    Cleaning up

    setwd(cwd)
    unlink(tmp, recursive = TRUE)