检索选择名称而不是值

tch*_*rty 8 r shiny

我有一个命名choices插槽selectInput,并希望检索与选择关联的名称,而不是值.

MWE:

shinyApp(
  ui = fluidPage(
    sidebarPanel(
    selectInput("foo",
                label = "Select choice here:",
                choices = c("Choice 1" = "Choice1",
                            "Choice 2" = "Choice2",
                            "Choice 3" = "Choice3"),
                selected = "Choice1",
                multiple = TRUE),
    textOutput("nameOfChoice")
  ),
  mainPanel()),
  server = function(input, output) {
    output$nameOfChoice = renderText(input$foo[1])
  }
)
Run Code Online (Sandbox Code Playgroud)

哪个产生:

在此输入图像描述

相反,我希望文本输出读取Choice 1.我怎样才能做到这一点?

nic*_*ola 7

把你的选择,在一个对象global.R,然后在都使用它server.Rui.R.

global.R:

fooChoices<-c("Choice 1" = "Choice1",
                        "Choice 2" = "Choice2",
                        "Choice 3" = "Choice3")
Run Code Online (Sandbox Code Playgroud)

ui.R:

selectInput("foo",
            label = "Select choice here:",
            choices = fooChoices) 
Run Code Online (Sandbox Code Playgroud)

server.R:

output$nameOfChoice = renderText(names(fooChoices[fooChoices==input$foo]))
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是一个合理的解决方案,但这很麻烦,因为这会将跟踪选择向量和输入对象槽名的负担传递给我 - 我宁愿Shiny这样做. (2认同)
  • 我没有收到你的评论.你只需给选择向量一个符号.而已.你认为什么是繁琐的? (2认同)