David
David

Reputation: 10222

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?

Upvotes: 0

Views: 1387

Answers (2)

Man.A.
Man.A.

Reputation: 31

A bit late, but I just figured a solution that works in RMarkdown:


output: html_document runtime: shiny

library(shiny)
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)

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

Upvotes: 1

Kota Mori
Kota Mori

Reputation: 6750

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)

Upvotes: 1

Related Questions