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

如何在R Shiny的RadioButton choiceNames中正确使用HTML

解决Shiny单选按钮HTML标签未渲染问题

问题场景

在Shiny应用中,希望根据文本框输入(如“A B C”)生成单选按钮,其标签需显示带希腊字母β和数字下标的格式(β₁j、β₂j、β₃j)。但直接传入HTML代码到choiceNames后,标签显示原始HTML代码而非渲染后的效果。

问题原因

原代码存在两处关键错误:

  • 错误地给HTML内容添加了额外的双引号包裹(paste0('"<div>',tempBeta,'</div>"')),导致HTML()对象被转为带引号的字符串,Shiny无法识别为可渲染的HTML
  • 构建choiceNames列表的方式不当,循环中拼接列表的逻辑导致HTML对象未被正确传递

修复后的代码

library(shiny) 

ui <- fluidPage( 
  sidebarLayout( 
    sidebarPanel( 
      textInput("Radio_Button_Choices", "输入单选按钮选项", ""),
      fluidRow(
        uiOutput('Select_Radio_Buttons')
      )
    ), 
    mainPanel( 
    ) 
  ) 
) 

server <- function(input, output, session) { 
  output$Select_Radio_Buttons <- renderUI({
    Radio_Button_selection <- unlist(strsplit(input$Radio_Button_Choices, "\\s+"))
    if (length(Radio_Button_selection) > 0) {
      # 用lapply生成带HTML解析的标签列表
      choiceNames <- lapply(seq_along(Radio_Button_selection), function(x) {
        HTML(paste0('&beta;<sub>', x, 'j</sub>'))
      })
      
      radioButtons("Model_Radio_Buttons","选择一个选项",
                   choiceNames = choiceNames,
                   choiceValues = Radio_Button_selection)
    }
  })
} 

shinyApp(ui, server) 

关键修改说明

  1. 移除多余引号:直接用HTML()包装纯HTML字符串,不需要额外添加双引号,确保Shiny能识别并渲染HTML内容
  2. 优化列表构建:使用lapply替代for循环,更简洁且能正确生成包含HTML对象的列表,每个标签都会被正确解析为带希腊字母和下标的格式
  3. 简化逻辑:去掉冗余的临时变量,直接生成所需的choiceNames列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:42:34