使用roxygen2在R脚本中添加公式,渲染为HTML时无法正常显示的问题求助
Let's break down the issues and fix them step by step:
1. Root Causes
- Escaped Underscores: Roxygen2 parses comments as Markdown by default, so underscores in your formula get escaped (e.g.,
d_Abecomesd\_A), breaking TeX syntax. - Backslash Mishandling: When reading the intermediate Markdown file, R treats backslashes as escape characters, leading to lost backslashes when the content is included in your main Rmd. This means MathJax can't recognize the valid TeX code.
2. Fix 1: Use Roxygen2's LaTeX Commands for Formulas
Instead of writing $$...$$ directly in roxygen comments, use roxygen2's \deqn{} command for display equations. This tells roxygen2 to treat the content as TeX, avoiding escaped underscores entirely.
In your script.R:
#' \\deqn{\\frac{d_{A}}{dt} = K_{rel} \\times A} #' # Rest of your R script code...
- Note the double backslashes: In R strings, backslashes must be escaped, so
\\becomes a single\when processed by roxygen2, which is exactly what TeX needs.
3. Fix 2: Modify the inline_render Function to Preserve Backslashes
Update your function to replace single backslashes with double backslashes when reading the intermediate Markdown file. This ensures that when the content is included in your main Rmd, MathJax receives valid, unbroken TeX syntax.
Modified function in your main Rmd:
inline_render <- function(script_name){ suppressMessages( rmarkdown::render(paste0(script_name, ".R"), output_format = "rmarkdown::md_document", quiet = TRUE) ) # Read the rendered Markdown file lines <- readLines(paste0(script_name, ".md")) # Replace single backslashes with double to preserve them in the final output lines <- gsub("\\\\", "\\\\\\\\", lines) # Join lines and print to the main Rmd cat(paste(lines, collapse = "\n"), "\n") }
quiet = TRUEsuppresses unnecessary rendering clutter.- The
gsubcall ensures every backslash is doubled, so when knitr processes the content, it retains the single backslash required for TeX to work.
4. Alternative: Use Math Fences in Roxygen Comments
If you prefer using $$...$$ or explicit math blocks, wrap your formula in a math code block in roxygen comments. This also prevents roxygen2 from escaping underscores:
In script.R:
#' ```math #' \\frac{d_{A}}{dt} = K_{rel} \\times A #' ``` #' # Rest of your R script code...
This renders to a dedicated math block in Markdown, which MathJax will interpret correctly (still requiring the gsub step in inline_render to preserve backslashes).
5. Verification
After making these changes:
- The intermediate Markdown file will have valid TeX without escaped underscores.
- The main Rmd will receive properly escaped backslashes, so MathJax renders the formula as a formatted equation instead of plain text.
内容的提问来源于stack exchange,提问作者Nacho Glez

