【问题标题】:Dynamically adding and removing objects in response to selectInput in Shiny动态添加和删除对象以响应 Shiny 中的 selectInput
【发布时间】:2018-02-01 14:55:51
【问题描述】:

我正在构建一个闪亮的应用程序来可视化一个大型地理数据集。我希望用户能够从下拉菜单中选择一个区域,然后复选框将出现在下拉菜单下方,其中包含第一个区域内较小地理区域的名称。然后,用户将能够单击每个复选框,该区域将在地图上突出显示,并向他们提供描述该区域的数据。

它几乎可以工作,除了一旦用户从下拉菜单中选择了一个区域并且复选框出现在其下方,如果他们随后在下拉菜单中更改他们的选择,则他们第一次选择的复选框不会删除。相反,第二组复选框出现在其上方。

以下是我的代码的相关部分:

UI.R

    ui <- fluidPage(

  sidebarPanel(
    selectInput(inputId = 'region', choices = c('All', admin1_regions_list), label = 'Select an admin1 region:'), #creates drop down menu, first argument is the id
    verbatimTextOutput('empty_box'), #creates empty box so that checkboxes will sit after it
  )
)

SERVER.R

server <- function(input, output){

observe({ # listens for input

    x <- input$region #input from drop down menu which has the id 'region'

      removeUI(selector = "div:has(> #admin2_checkboxes)", immediate = TRUE)      

      insertUI(
        selector = '#empty_box', #empty box is used as placeholder, sits just below first drop down menu in ui
        where = 'afterEnd', #where in relation to empty box should the checkbox input be
        ui = checkboxGroupInput(inputId = 'admin2_checkboxes', label = 'Select an admin2 region:',
                            choices = admin2_list)
          )
})
})

我认为在插入新函数之前立即调用 removeUI() 函数会做我想要的,但它似乎没有做任何事情。这是因为选择器不正确吗? (我也将它设置为"div:has(&gt; #empty_box)",即与inputUI() 函数调用相同的选择器,但这也不起作用)。还是我需要重构我的代码?

【问题讨论】:

  • 你能提供一个可重现的例子吗?

标签: r shiny


【解决方案1】:

我无法运行您的代码,并且之前没有使用过您的方法来解决此问题。但是,以下示例有一个基于所选汽车品牌的动态更新组复选框。那是你所追求的功能吗(如果不是方法)。

library(shiny)

ui <- fluidPage(
  
  sidebarPanel(
    selectInput('make', choices = c("-", "Merc", "Cadillac", "Fiat"), label = 'Select a car make:'), #creates drop down menu, first argument is the id
    conditionalPanel(condition = "input.make != '-'",
                     uiOutput("select_car"))
  )
)


server <- function(input, output) {
  
  output$select_car <- renderUI({
    
    choices <- rownames(mtcars)[grep(input$make, rownames(mtcars))]
    
    checkboxGroupInput('cars', label = 'Select cars:',
                       choices = choices)
  })
  

}

shinyApp(ui, server)

【讨论】:

  • 没问题 - 很高兴为您提供帮助!
猜你喜欢
  • 2019-01-19
  • 2021-06-20
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
相关资源
最近更新 更多