rshinyr-markdownmathjax

Insert spaces in equation in R Shiny application with mathjax


I would like to make a shiny app where I display equations with Mathjax. But they don't look good because there are no spaces put between any of the equation terms. Here's my code with the equation inside the renderText statement. I'm using the equation in Shiny, but am getting the mathjax code for rendering by putting the raw equation into an R Markdown document and using the mathml library's "mathout" function to produce the code for the equation in the function. Perhaps that is what I am doing wrong.

library(shiny)

ui <- fluidPage(
        title = 'MathJax Examples',
        uiOutput('ex3'))

server <- function(input, output, session) {
             output$ex3 <- renderUI({
             withMathJax(
             renderText("$${610.70}{\\cdot}{\\exp{\\left[{\\left({17.38}{{}} 
                        {ta}\\right)}{/}{\\left({239.00}{+}{ta}\\right)}\\right]}}$$"))
})}

shinyApp(ui = ui, server = server)

The output looks like this: 610.70⋅exp[(17.38ta)/(239.00+ta)]

There are similar questions on Stackoverflow, I realize, but I can't get their suggestions to work. I would like to get output that looks like this:

610.70 * exp[(17.38 * ta)/(239.00 + ta)]

I should add that I get an escape error if I use single backslashes. If I do '\cdot' instead of '\cdot'. for example:

Error: '\c' is an unrecognized escape in character string 
(<input>:4:31)

Solution

  • I strongly advise against manually fiddling with the spaces in a mathematical equation (unless you know exactly what you are doing): in general, MathJax knows better than you.

    This means: remove all braces from your equation: they tell MathJax not to apply the regular spacing rules. Braces are only necessary for grouping of sub-expressions to override the usual operator precedence rules. This does not apply in your case.

    Furthermore, it is generally advised to use \middle/ instead of plain / to render a solidus fraction — for the same reason as using \left(…\right) instead of plain (…) (although in your case it doesn’t make a difference). Alternatively, use \frac{…}{…} for a stacked fraction.

    Compare (press Run code snippet below to see the output):

    <script type="text/javascript" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    
    Original:
    
    $${610.70}{\cdot}{\exp{\left[{\left({17.38}{{}} 
                        {ta}\right)}{/}{\left({239.00}{+}{ta}\right)}\right]}}$$
    
    Corrected:
    
    $$
      610.70 \cdot \exp{\left[
        \left( 17.38 ta \right) \middle/
        \left( 239.00 + ta \right)
      \right]}
    $$
    
    Using stacked fraction:
    
    $$
      610.70 \cdot \exp \frac{17.38 ta}{239.00 + ta}
    $$