我想以清晰的格式显示R等式,以查看公式.
比方说我有:
A=B/C
Run Code Online (Sandbox Code Playgroud)
我想知道是否有某种方式可以显示它,就像乳胶输出中显示的那样:
$A=\frac{B}{C}$
Run Code Online (Sandbox Code Playgroud)
raw*_*awr 15
很可能这已存在于某个地方,但您可以编写一个函数来使用mathjax呈现公式并在查看器中显示它(如果您使用的是rstudio)或在Web浏览器中显示.如果您想要动态编辑/检查公式,这将有所帮助
form1 <- '$$A=\\frac{B}{C}$$'
form2 <- '$$
\\frac{1}{\\displaystyle 1+
\\frac{1}{\\displaystyle 2+
\\frac{1}{\\displaystyle 3+x}}} +
\\frac{1}{1+\\frac{1}{2+\\frac{1}{3+x}}}
$$'
form3 <- '\\frac{d}{dx}\\left( \\int_{0}^{x} f(u)\\,du\\right)=f(x)'
show_math(form1)
Run Code Online (Sandbox Code Playgroud)

如果您不使用rstudio,请在浏览器中打开
show_math(form2, use_viewer = FALSE) ## opens in default browser
Run Code Online (Sandbox Code Playgroud)

show_math(form1, form2, form3, css = 'color: red; font-size: 15px;')
Run Code Online (Sandbox Code Playgroud)

我很确定mathjax不完全支持乳胶方程式.并且一定要逃避\公式
您还可以显示多条很酷的线路.
form4 <- "
\\forall a,b,c \\in \\mathbb{R} \\\\
\\begin{align}
a + b &= c \\\\
(a + b)(a - b) &= c(a - b) \\\\
a^2 - b^2 &= ca - cb \\\\
a^2 - ca &= b^2 - cb \\\\
a^2 - ca + \\frac{c^2}{4} &= b^2 - cb + \\frac{c^2}{4} \\\\
(a - \\frac{c}{2})^2 &= (b - \\frac{c}{2})^2 \\\\
a - \\frac{c}{2} &= b - \\frac{c}{2} \\\\
a &= b \\qquad \\qquad \\blacksquare \\\\
\\end{align}
"
show_math(form4)
Run Code Online (Sandbox Code Playgroud)

show_math <- function(..., css, use_viewer = !is.null(getOption('viewer'))) {
mj <- "<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>"
## view text strings as html in viewer/browser
view_html <- function(..., viewer) {
x <- c(...)
if (is.null(x)) return(invisible())
htmlFile <- tempfile(fileext = '.html')
writeLines(x, con = htmlFile)
if (viewer)
tryCatch(rstudio::viewer(htmlFile),
error = function(e) {
message('Viewer not available - opening in browser.\n',
'If using Rstudio, try installing the \'rstudio\' package.',
domain = NA)
browseURL(htmlFile)
})
else browseURL(htmlFile)
invisible(x)
}
## use \[ expr \] instead of $$ expr $$
check_expr <- function(x)
sprintf('\\[%s\\]', gsub('^\\$+|\\$+$', '', x))
x <- paste(sapply(c(...), check_expr), collapse = '<br />')
if (!nzchar(x)) return(invisible())
if (missing(css)) css <- ''
## setting the default to larger font since @Molx has bad eyes :}
## this can still be over-ridden by passing font-size: whatever; to css
view_html(sprintf('<span class="math" style="font-size: 24px; %s;">\n', css),
x, '\n</span>\n', mj, viewer = use_viewer)
}
Run Code Online (Sandbox Code Playgroud)