Search code examples
rshinymathjax

Render Dynamic Equations in Shiny


I have a shiny-document that should explain some maths and calculate the result given some shiny-inputs.

If I knit the document everything works until I change an input and the mathjax/latex code is shown instead of the proper rendered equations.

A minimum working example is this (test.Rmd)

---
output: html_document
runtime: shiny
---

```{r,,echo=F}
library(shiny)
```

```{r,echo=F}
numericInput("a", "A", value = 100, min = 0, max = 10000)
numericInput("b", "B", value = 120, min = 0, max = 10000)
a <- reactive(input$a)
b <- reactive(input$b)

renderText(withMathJax({
  formula <- "$$
\\begin{split}
A &= %.0f \\\\
B &= %.0f 
\\end{split}
$$"
  text <- sprintf(formula, a(), b())

  return(text)
}))
```

What I expect to see is this (which I get before I change an input)

Correct Picture

after I change A or B, I get this

Broken Picture

Any idea on how to solve this or what I did wrong?


Solution

  • Here is a working example. Make sure you see this on a browser.

    library(shiny)
    
    ui <- list(
      numericInput("a", "A", value = 100, min = 0, max = 10000),
      numericInput("b", "B", value = 120, min = 0, max = 10000),
      uiOutput('out')
    )
    
    server <- function(input, output) 
    {
      a <- reactive(input$a)
      b <- reactive(input$b)
      output$out <- renderUI({
        formula <- "$$
          \\begin{split}
          A &= %.0f \\\\
          B &= %.0f 
          \\end{split}
          $$"
        text <- sprintf(formula, a(), b())
        withMathJax(  
          tags$p(text)
        )
      })
    }
    
    shinyApp(ui, server)