闪亮:如何在服务器 datasetInput 开关的 ui selectInput 选项中遍历变量名?

Shiny: How can I loop thru variable names in the ui selectInput choices in the server datasetInput switch?

在 Shiny 中,我只想 select 绘制数据帧的哪个变量,我不想在服务器切换部分键入所有变量名称。这是我的工作:

ui <- fluidPage(
  titlePanel("Hello World!"),
  sidebarLayout(
    sidebarPanel(
      selectInput("variable", "Choose a variable:",
                  # choices = c("cyl", "mpg")),
                  choices = names(mtcars)),
    ),
    mainPanel(
      plotOutput(outputId = "BarPlot"),
    )
  )
)

server <- function(input, output) {
  datasetInput <- reactive({
    switch(input$variable,
           "cyl" = mtcars[,"cyl"],
           "mpg" = mtcars[,"mpg"])
  })
  output$BarPlot <- renderPlot({
    x    <- datasetInput()
    barplot(table(x))
  })
}

而不是

switch(input$variable,
       "cyl" = mtcars[,"cyl"],
       "mpg" = mtcars[,"mpg"])

我可以做类似的事情吗

choices = mtcars[,get(choices)]

无需一一键入即可涵盖所有选项?

一种方法是使用 varSelectInput 并将数据框作为 data 传递(它将包括所有列名称作为选择)。然后,您可以在示例中从 mtcarsmtcars[[input$variable]] 中提取所选列:

library(shiny)

ui <- fluidPage(
  titlePanel("Hello World!"),
  sidebarLayout(
    sidebarPanel(
      varSelectInput("variable", 
                     "Choose a variable:",
                     data = mtcars),
    ),
    mainPanel(
      plotOutput(outputId = "BarPlot"),
    )
  )
)

server <- function(input, output) {
  datasetInput <- reactive({
    mtcars[[input$variable]]
  })
  output$BarPlot <- renderPlot({
    x    <- datasetInput()
    barplot(table(x))
  })
}

shinyApp(ui, server)