You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny根据SelectInput选择动态输出MathJax数学公式的实现问题

问题解决方法

你原来的代码存在两处核心错误,修改后即可正常渲染数学公式:

核心修改点

  • withMathJax() 属于UI层依赖,不能放在server函数中,需要放到UI部分加载,才能让页面正常引入MathJax渲染引擎
  • 不能用textOutput()+renderText()组合输出带公式的内容:这组函数只会输出纯文本,不会触发MathJax的公式解析,需要替换为uiOutput()+renderUI()组合

修正后的完整可运行代码

library(shiny)
ui <-navbarPage(title = "test",
                # UI层引入MathJax依赖
                withMathJax(),
                helpText("Here we select which parameters we want to include in our model"),
                selectInput("torchp",  
                            label = h4("Torching Parameters"), 
                            choices = list("One parameter", 
                                           "Two parameters" ), 
                            selected = 1),
                mainPanel(
                  # 替换textOutput为uiOutput
                  uiOutput("torchvalue")
                )
)

server <- function(input, output) {
  torchp_input <- reactive({
    switch(input$torchp,
           "One parameter" = '$$q$$', 
           "Two parameters" = '$$q_m, q_f$$'
    )
  })
  
  # 替换renderText为renderUI
  output$torchvalue <- renderUI({ 
    tagList("You have selected", HTML(torchp_input()))
  })
}

shinyApp(ui = ui, server = server)

补充说明

如果需要在公式外拼接其他普通文本,也可以直接把普通文本和公式语法写到同一个字符串里,MathJax会自动识别$$包裹的部分做公式渲染,示例如下:

output$torchvalue <- renderUI({ 
  HTML(paste0("You have selected ", torchp_input()))
})

内容的提问来源于stack exchange,提问作者Fay Frost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:15:03