【发布时间】:2020-08-25 05:14:35
【问题描述】:
可能是非常基本的问题 - 但无法将我发现的类似帖子翻译成我的确切问题。
在 R Shiny 应用程序中,我有一个由服务器上生成的向量填充的第一个下拉菜单 - 这使我可以做出一组选择。
我想要一个复选框,然后引入第二个下拉菜单 - 但如果我取消勾选复选框,我希望该下拉菜单消失。
我已经尝试过 - 请参阅下面的 MWE - 该图只是为了保持我的原始代码的结构(显然我知道我的下拉菜单什么都不做,但原始情况并非如此,但想要MWE 尽可能为“M”)。
如果我删除了 removeUI() 行,那么勾选复选框确实会根据需要创建一个新的下拉列表 - 但是取消勾选复选框无法将其删除。
我显然遗漏了一些东西;非常感谢任何帮助,因为我完全不喜欢 R Shiny,但真的想变得更好!
library(shiny)
library(shinyMobile)
# define UI elements
ui <- f7Page(
f7SingleLayout(
navbar = f7Navbar(
),
f7Card(htmlOutput("initial_drop_down"), #first drop down
f7checkBox(inputId = "switch", label = "Introduce second choice", FALSE), #tick box for second drop down if required
htmlOutput("reactive_drop_down") #second drop down
),
f7Shadow(
intensity = 16,
f7Card(
plotOutput("distPlot", height = "800px") # plot - originally linked to drop down choices but an arbitrary graph here for simplicity
)
)
)
)
# server calculations
server <- function(input, output) {
library(ggplot2)
# generate first drop down - done on server side since usually choices vector is comprised of information read in from files
output$initial_drop_down = renderUI({
selectInput(inputId = "initial_choice",
label = "First choice:",
choices = c("Choice 1", "Choice 2", "Choice 3"))
})
observeEvent(input$initial_choice, {
# trying to add second drop down based on action in switch - not convinced my use of observeEvent is quite right - issue likely sits in here.
observeEvent(input$switch, {
if(input$switch == T){
output$reactive_drop_down = renderUI({
selectInput(inputId = "second_choice",
label = "Second (dynamic) choice:",
choices = c(1,2,3))
})
}else{
removeUI(selector ="#reactive_drop_down")
}
})
output$distPlot <- renderPlot({
ggplot(data = cars) + geom_line(aes(x=speed, y=dist))
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
【问题讨论】: