How to get \bm{} to work in an R markdown (to HTML) file?

后端 未结 4 2025
误落风尘
误落风尘 2021-02-08 00:42

My R Markdown (.Rmd) file looks like this:

---
title: Foo
author: Marius Hofert
header-includes:
    - \\usepackage{bm}
output:
    pdf_document
vignette: >
          


        
4条回答
  •  囚心锁ツ
    2021-02-08 01:19

    A third solution works well if you are using Mathjax to render equations in your html docs. Mathjax is on by default in pandoc in RStudio. This has the advantage of no flickering and works in $$ $$ and the equation environment. The big downside to this is that pandoc strips \ref{} out of the html so you have to add a knit hook to change to \ref{}. Surely there is a way to tell pandoc not to do this, but I couldn't find it. I tried many different pandoc args with no success.

    This example assumes you want equation numbers and you want to crossref those in your text. It also assumes you are knitting from RStudio. Probably works otherwise, but that is what I tested in.

    mathjax.js --- define the macros here and tell Mathjax to add eqn #s

    
    
    

    defs.tex --- this is for pdf_document

    \def\AA{\bf A}
    \def\BB{\bf B}
    

    test.Rmd --- now we can make Rmd docs that work with html and pdf. I could not figure out how to tell pandoc not to strip LaTeX commands out of the html. So passed in a knit hook to double \ the \ref{} calls.

    ---
    title: "Test"
    knit: ( function(inputFile, encoding) { if(rmarkdown::all_output_formats(inputFile)[1]=="html_document"){ f <- inputFile; x <- readLines(f); y <- gsub("[\\]ref[{]","\\\\\\\\ref{", x); cat(y,file="tmp.Rmd", sep="\n"); rmarkdown::render("tmp.Rmd", encoding = encoding ) }else{ rmarkdown::render(inputFile, encoding = encoding ) } })
    output: 
      html_document:
        includes:
          before_body: [../tex/mathjax.html]
      pdf_document: 
        includes: 
          before_body: ../tex/defs2.tex
    ---
    
    ```{r mss-setup, include=FALSE, purl=FALSE}
    knitr::opts_knit$set(unnamed.chunk.label = "tvarss-")
    ```
    
    In the pdf, this will not have a number but in the html it will.
    
    $$
    \AA^\top\BB
    $$
    You can use nonumber if you need the equation numbering to be the same in html and pdf.
    
    $$
    \AA^\top\BB\nonumber
    $$
    
    If we want to crossref an equation, use equation environment.  
    \begin{equation}
    \AA^\top\BB
    \label{eqn1}\end{equation}
    This is Equation \ref{eqn1}.
    

    Here is the knit function:

    ( function(inputFile, encoding) { if(rmarkdown::all_output_formats(inputFile)[1]=="html_document"){ f <- inputFile; x <- readLines(f); y <- gsub("[\]ref[{]","\\\\ref{", x); cat(y,file="tmp.Rmd", sep="\n"); rmarkdown::render("tmp.Rmd", encoding = encoding ) }else{ rmarkdown::render(inputFile, encoding = encoding ) } })

提交回复
热议问题