2

下面的 R 闪亮脚本创建了三个 selectInput,这样每个 selectInput 的值取决于前一个 selectInput 的输入值。例如,在脚本中的数据中,“value”列的值取决于“Candy”列,“Candy”列的值取决于“Brand”。问题是,无论我在“品牌”列中选择“火星”还是“荨麻”值,对应的“糖果”值“100Grand”都是相同的,因此我看不到值列中的变化selectInput 正在读取相同的值。请帮我解决这个问题,还请确保脚本不会变慢。谢谢。

candyData <- read.table(
text = "
Brand       Candy           value
Mars        100Grand        Choc1
Netle       100Grand        Choc2
Nestle      Crunch          Choc3",
header = TRUE,
stringsAsFactors = FALSE)
library(shiny)
library(shinydashboard)
submenuUI <- function(id) {
ns <- NS(id)
tagList(
box(title = "Data", status = "primary", solidHeader = T, width = 12,
    fluidPage(
      fluidRow(

        column(2,offset = 0, style='padding:1px;',

selectInput(ns("Select1"),"select1",unique(candyData$Brand))),
        column(2,offset = 0,

style='padding:1px;',selectInput(ns("Select2"),"select2",choices = NULL)),
        column(2, offset = 0,

style='padding:1px;',selectInput(ns("Select3"),"select3",choices=NULL ))
      )))
)
}
submenuServ <- function(input, output, session){
observeEvent(input$Select1,{
updateSelectInput(session,'Select2',
choices=unique(candyData$Candy[candyData$Brand==input$Select1]))
})
observeEvent(input$Select2,{
updateSelectInput(session,'Select3',
choices=unique(candyData$value[candyData$Brand==input$Select1 &
candyData$Candy==input$Select2]))
})
}
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
sidebarMenu(
  shinyjs::useShinyjs(),
  id = "tabs",
  menuItem("Charts", icon = icon("bar-chart-o"),
           shinyjs::hidden(menuSubItem("dummy", tabName = "dummy")),
           menuSubItem("Sub-item 1", tabName = "subitem1")
  ))),
dashboardBody(
tabItems(tabItem("dummy"),
         tabItem("subitem1", submenuUI('submenu1'))
)
))
server <- function(input, output,session) {
callModule(submenuServ,"submenu1")
}
shinyApp(ui = ui, server = server)

选择输入问题

4

1 回答 1

4

您可以添加input$Select1observeEvent的更新选择3

submenuServ <- function(input, output, session){
    observeEvent(input$Select1,{
        updateSelectInput(session,'Select2',
                          choices=unique(candyData$Candy[candyData$Brand==input$Select1]))
    })
    observeEvent(c(input$Select1, input$Select2),{
        updateSelectInput(session,'Select3',
                          choices=unique(candyData$value[candyData$Brand==input$Select1 &
                                                             candyData$Candy==input$Select2]))
    })
}

如果需要,可以将其转换observeEventobserve

observe({
    updateSelectInput(
        session, 'Select3',
        choices= unique(candyData$value[candyData$Brand==input$Select1 & candyData$Candy==input$Select2])
    )
})
于 2018-01-30T11:00:19.710 回答