R Shiny - 获取单选按钮的标签

问题描述 投票:0回答:1

我试图在单选按钮中提取所选选项的标签。例如,我有一个名为'dist'的单选按钮,选中的选项是'norm'

ui <- fluidPage(
  radioButtons("dist", "Distribution type:",
               c("Normal" = "norm",
                 "Uniform" = "unif",
                 "Log-normal" = "lnorm",
                 "Exponential" = "exp")),
  plotOutput("distPlot")
)

server <- function(input, output) {
  x1 = input$dist
  print(x1) # gives 'norm' but I want 'Normal'
}

shinyApp(ui, server)

我想知道最简单的方法来实现它,而不使用任何外部构造,如JavaScript等。

r shiny radio-button label
1个回答
0
投票

首先,提供的代码不起作用 - 服务器代码需要包装在observe({ ... })中才能运行。

至于你的问题 - 有两种方法可以解决这个问题。

  1. 如果选项是提前知道的并且不是动态的,则可以将选项列表定义为可供UI和服务器访问的单独变量(如果ui和服务器在单独的文件中定义,则将其放入一个global.R文件)。然后只需根据值查找名称。 dist_options <- c("Normal" = "norm", "Uniform" = "unif", "Log-normal" = "lnorm", "Exponential" = "exp") ui <- fluidPage( radioButtons("dist", "Distribution type:", dist_options), plotOutput("distPlot") ) server <- function(input, output) { observe({ x1 = input$dist print(names(which(dist_options == x1))) }) } shinyApp(ui,server)
  2. 如果选项是动态的,您将需要参与自定义JavaScript代码。 Shiny将需要ask javascript基于其值的特定输入的标签值,并且javascript将需要communicate it back to shiny
© www.soinside.com 2019 - 2024. All rights reserved.