使用 if-else Rshiny 从下拉列表中进行多项选择

Multiple Selection From Dropdown Using if-else Rshiny

我正在尝试根据用户输入创建两个下拉菜单。如果用户选择“val1”,则在“x”的第二个下拉列表中显示值。如果是“val2”,则为“y”。如果“val1”和“val2”都存在,则 z.

至此,除了多选部分,我都成功了。我也试过:

else if (input$lab == "val1" & input$lab == "val2")

这给了我同样的错误:

the condition has length > 1 and only the first element will be used

x <- c("x1", "x2", "x3")
y <- c("y1", "y2", "y3")
z <- c("x1", "x2", "x3", "y1", "y2", "y3")
library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
  dashboardHeader(title = "title"),
  
  dashboardSidebar(
    sidebarMenu(
      menuItem("xxx", tabName = "tab1")
    )
  ),
  
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "tab1",
        pickerInput("dropdown1", "Values:", choices = c("x", "y"), multiple = T),
        uiOutput("dropdown2")
      )
    )
  )
)

server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)
    
    if (input$dropdown1 == "x") {
      x
    }
    
    else if (input$dropdown1 == "y") {
      y
    }
    
    else if (input$dropdown1 == "x" && input$dropdown1 == "y") {
      z
    }
  })
  
  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })
}

shinyApp(ui, server)

您服务器的方法略有变化。与其用 ifelse 来测试 x、y 或 x&y,不如测试 length == 1,然后在这种情况下,无论是 x 还是 y。

server <- function(input, output, session) {
  values <- reactive({
    req(input$dropdown1)
    
    if (length(input$dropdown1) == 1) {
      if (input$dropdown1 == "x") {
        c("x1", "x2", "x3")
      }
      else {
        c("y1", "y2", "y3")
      }
    }
    else {
      c("x1", "x2", "x3", "y1", "y2", "y3")
    }
  })
  
  output$dropdown2 <- renderUI({
    pickerInput("dropdown2", "Values:", choices = values())
  })
  
}

根据“x”和“y”中的实际内容,使用 ifelse() 可能会在这种方法中为您节省 space。