Latex equation not rendering correctly in shiny

204 views Asked by At

I want to display a latex equation in a shiny application. I saw an example where mathjax is used to display latex equations. But for some reason the equation generated from equatiomatic package does not display correctly. Following is a reproducible example:

library(shiny)
library(tidyverse)
library(broom)
library(equatiomatic)


## Loading Dataset
data(mpg)


mpg2 <- mpg %>% 
  select(where(is.numeric))




## User Interface
ui <- fluidPage(
  withMathJax(),
  sidebarPanel(
  selectInput(inputId = "xcol", 
              label = "Select an explanatory variable", 
              choices = colnames(mpg2), 
              selected = "cty"),
  
  selectInput(inputId = "ycol", 
              label = "Select a response variable", 
              choices = colnames(mpg2), 
              selected = "hwy")
  ),
  
  mainPanel(
    plotOutput('plot'),
    br(),
    uiOutput('eq'),
    br(),
    tableOutput('table1'),
    br(),
    tableOutput('table2')
  )
  
)



## Server
server <- function(input, output, session) {
  
  data <- reactive({
    
   mpg2 %>% 
      select(col1 = input$xcol, col2 = input$ycol)

  })
  

  
  output$plot <- renderPlot({
    

    
    ggplot(data()) +
      geom_point(aes(col1, col2)) +
      labs(x = input$xcol, y = input$ycol)
      
    
  })
  
  
  output$table1 <- renderTable({
    
    m1 <- lm(reformulate(input$xcol, input$ycol), data = mpg2)
    
    broom::tidy(m1)
    
  })
  
  
  output$table2 <- renderTable({
    
    m1 <- lm(reformulate(input$xcol, input$ycol), data = mpg2)
    
    broom::glance(m1)[, 1:2]
    
  })
  
  
  
  output$eq <- renderUI({
    
    m1 <- lm(reformulate(input$xcol, input$ycol), data = mpg2)
    
    withMathJax(helpText(extract_eq(m1)))
  })
  
  
}

shinyApp(ui, server)
1

There are 1 answers

1
SEcker On BEST ANSWER

Interesting, it seems like shiny is expecting the equation as raw character string. Hence it is missing a \ for all Latex operators.

One (not very pretty) way to fix it would be:

    output$eq <- renderUI({
    
    m1 <- lm(reformulate(input$xcol, input$ycol), data = mpg2)
    
    withMathJax(helpText(
                         paste0("$$", as.character(extract_eq(m1)), "$$")
                         )
                )
})

However I am not too familiar with the package so not sure if this is intended or a bug... Have you considered opening an issue at the equatiomatic GitHub?