Search code examples
rshinyshinydashboardshiny-servershinyapps

How to set column names as mathematical formulas in data.frame in Shiny?


I am new to Shiny, and I ran into the following problems:

I want to output the column names in a mathematical form, which means, in the table below, y1---> y1......and y_--->. I don't know if this is feasible, I have used many methods, but I haven't found a better one yet.

Part of my code is as follows:

  yValues <- reactive({
     data.frame(
       Group=c("1"),
       y1=as.character(c(input$meansy1)),
       y2=as.character(c(input$meansy2)),
       y3=as.character(c(input$meansy3)),
       y4=as.character(c(input$meansy4)),
       y5=as.character(c(input$meansy5)),
       y6=as.character(c(input$meansy6)),
       y_=as.character(c(y_mean())),
       y.Variance=as.character(c(y_Variance())),
       stringsAsFactors=FALSE)
  })

This is the table now:

Output Table


Solution

  • Here is a way with KaTeX. Put your math code between two pairs of %%.

    library(shiny)
    
    js <- " 
    $(document).on('shiny:value', function(event) {
      if(event.name === 'table'){
        var matches = event.value.match(/(%%+[^%]+%%)/g);
        var newvalue = event.value;
        for(var i=0; i<matches.length; i++){
          var kcode;
          var x = matches[i].slice(2,-2);
          try{
            var code = '\\\\' + x;
            kcode = katex.renderToString(code)
          } catch(error){
            kcode = katex.renderToString(x)
          }
          newvalue = newvalue.replace(matches[i], kcode);
        }
        event.value = newvalue;
      }
    })
    " 
    
    ui <- fluidPage(
      tags$head(
        tags$link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css", integrity="sha384-9tPv11A+glH/on/wEu99NVwDPwkMQESOocs/ZGXPoIiLE8MU/qkqUcZ3zzL+6DuH", crossorigin="anonymous"),
        tags$script(src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js", integrity="sha384-U8Vrjwb8fuHMt6ewaCy8uqeUXv4oitYACKdB0VziCerzt011iQ/0TqlSlv8MReCm", crossorigin="anonymous"),
        tags$script(HTML(js))
      ),
      titlePanel("Hello Shiny!"),
      mainPanel(
        tableOutput("table")
      )
    )
    
    server <- function(input, output) {
      
      yValues <- reactive({
        data.frame(
          Group      = "1",
          "%%y_1%%"  = LETTERS[1:3],
          "%%bar{y}%%" = letters[1:3],
          stringsAsFactors = FALSE,
          check.names = FALSE)
      })
      
      output[["table"]] <- renderTable({
        yValues()
      }, rownames = TRUE)
      
    }
    
    shinyApp(ui, server)
    

    enter image description here