【问题标题】:Can I use a radio button selection in one part of the UI to create a heading?我可以在 UI 的一部分中使用单选按钮选择来创建标题吗?
【发布时间】:2021-05-28 02:22:12
【问题描述】:

我想做的是根据用户选择的内容为面板生成一个标题。例如,如果用户选择“z”的单选按钮,我希望面板的标题显示“z”。

我知道我可以使用很多 conditionalPanel 语句到达那里,例如 conditionalPanel(condition="input.choice_crit==1",h3("First Choice")) 或其他什么,但使用起来会更优雅我已经放入单选按钮选择列表的名称。如果我在某个时候添加其他内容,更新会更容易。

所以这段代码可以工作,但显然不是动态的。有没有办法将 [3] 替换为单选按钮中已选择的任何内容,以便 h3() 填充选择时从choice_crit 中选择的适当名称?

library(shiny)

choice_crit <- c(1, 2, 3, 4)
names(choice_crit) <- c("z","t","\U1D6D8\U00B2","F")


# Define UI
ui <- fluidPage(


    # Sidebar
    sidebarLayout(
        
        sidebarPanel(
            h3(names(choice_crit[3])),
            radioButtons(inputId = "crit_select",label = "Select the statistic:",choices = choice_crit),
        ),

        # Main output
        mainPanel(
           
        )
    )
)

# Define server logic
server <- function(input, output) {


}

# Run the application 
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    这是你想要的吗?您可以使用renderUIuiOutput 来实现它。

    
    library(shiny)
    
    choice_crit <- c(1, 2, 3, 4)
    names(choice_crit) <- c("z","t","\U1D6D8\U00B2","F")
    
    
    # Define UI
    ui <- fluidPage(
      
      
      # Sidebar
      sidebarLayout(
        
        sidebarPanel(
          uiOutput("title"),
          radioButtons(inputId = "crit_select",
                       label = "Select the statistic:", 
                       choices = choice_crit),
        ),
        
        # Main output
        mainPanel(
          
        )
      )
    )
    
    # Define server logic
    server <- function(input, output) {
      output$title <- renderUI({
        h3(names(choice_crit)[as.numeric(input$crit_select)])
        #h3(names(choice_crit)[as.character(choice_crit) == input$crit_select]) # Alternative
      })
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    
    

    另外,您应该注意 radioButtions 的文档:

    choices:要从中选择的值列表(如果列表的元素已命名,则向用户显示该名称而不是值)。如果提供了此参数,则不得提供choiceNames 和choiceValues,反之亦然。 值应该是字符串;其他类型(例如逻辑和数字)将被强制转换为字符串。

    因此input$crit_select 最终成为一个character 向量,取值"1""4"

    【讨论】:

    • 完美,谢谢!感谢您考虑添加有关选择的说明。
    【解决方案2】:

    一种方法是您可以在 UI 中将 h3 包装在 uiOutput 中:

    uiOutput("h3ui"),
    

    在服务器中:

    output$h3ui <- renderUI({
     HTML(paste0("<h3>",input$crit_select,"</h3>"))
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多