R shinyapp 从复选框中选择预存储的数据集

R shinyapp selecting pre-stored data set from checkbox

ui <- fluidPage(
    checkboxGroupInput("data", "Select data:",
                       c("Iris" = "iris",
                         "Cars" = "mtcars")),
    plotOutput("myPlot")
  )

  server <- function(input, output) {
    output$myPlot <- renderPlot({
      plot(Sepal.Width ~ Sepal.Length, data = input$data)
    })
  }

  shinyApp(ui, server)

我有一个 shinyApp,我希望用户在其中 select 一个数据集。从那里,我想使用该数据集来制作一个简单的图。但是,用户在复选框中的输入似乎没有成功传递到 server。我该如何解决这个问题?

在 shiny 中执行此操作的典型方法是使用 switch(),这意味着您无需在输入中指定数据集,您可以在服务器中完成所有操作。在您的上下文中:

library(shiny)
ui <- fluidPage(
  checkboxGroupInput("data", "Select data:",
                     c("Iris" = "iris",
                       "Cars" = "mtcars")),
  plotOutput("myPlot")
)

server <- function(input, output) {
  dat <- reactive({
    switch()
  })
  output$myPlot <- renderPlot({
    dat <- switch(input$data, 
                  "iris" = iris,
                  "mtcars" = mtcars)
    plot(Sepal.Width ~ Sepal.Length, data = get(input$data))
  })
}

shinyApp(ui, server)

请注意,您可以在 checkboxGroupInput 中使用任何字符串,这使得这种工作方式更加灵活。