【发布时间】:2020-03-20 16:55:19
【问题描述】:
我想在 Shiny 的条件面板上进行类似 while 循环的东西,其中循环的条件基于先前的输入。
详细信息:用户选择他想开始的国家和他想结束的另一个国家。他们还需要选择路线应该通过的边界。我想要实现的是首先更新选择输入中的选择,因此第一个仅包含国家“从”的边界,然后是他们选择去的国家的边界等。另外,我想要第二个和以下选择输入仅显示直到用户选择与国家“To”的边界为止。
我想到了下面的伪代码:
bord_to=sub(".*-", "", input$b_dir_1)
i=2
while(bord_to!=input$cou_to){
conditionalPanel(condition = 'bord_to != input$cou_to',
selectInput("b_dir[i]",
"",
"")
bord_to=sub(".*-", "", input$b_dir[i])
i=i+1
}
我还想将输入命名为“b_dir_i”。
我创建了以下代码,它至少可以处理更新输入,但我仍然错过了有条件地显示输入的方法:
library(shiny)
countries <- c( "AT", "BG", "CH", "CZ", "DE", "FR", "GR", "HR", "HU", "IT-GREC", "IT-NORD", "PL", "RO", "RS", "SI", "SK", "TR" )
borders <- c( "MK-RS", "RS-MK", "AL-GR", "GR-AL", "AL-ME", "ME-AL", "BA-HR", "HR-BA", "BA-ME", "ME-BA", "GR-MK", "MK-GR", "GR-TR", "TR-GR", "RS-BA", "BA-RS", "HU-RS", "RS-HU", "RO-RS", "RS-RO", "HU-UA", "UA-HU", "SK-UA", "UA-SK", "AT-CZ", "CZ-AT", "AT-HU", "HU-AT", "DETE-CZ", "CZ-DETE", "HR-HU" , "HU-HR", "HR-SI", "SI-HR" , "HR-RS", "RS-HR", "GR-IT", "IT-GR", "CH-IT", "IT-CH", "CH-FR" , "FR-CH", "CH-AT", "AT-CH", "CH-DE", "DE-CH", "DE50-CZ", "CZ-DE50", "PL-CZ", "CZ-PL", "DE50-PL", "PL-DE50", "PL-SK", "SK-PL", "BG-MK", "BG-TR", "MK-BG", "TR-BG", "BG-RS", "RS-BG", "BG-GR", "GR-BG", "RO-BG", "BG-RO" )
ui<-fluidPage(
fluidRow( column( 6,
h4("Select countries:"),
selectInput("cou_from", "From:", c("", countries)),
selectInput("cou_to", "To:", c("", countries)) ) ),
h4("Select borders:"),
fluidRow(
column( 3, selectInput("b_dir_1", "", ""), ),
# this is the fragment I want to go on the loop
column( 3,
conditionalPanel(
condition = 'sub(".*-", "", input$b_dir_1) != input$cou_to ',
selectInput("b_dir_2", "", "") ) ) ),
actionButton( "run_anl",
"Run Analysis",
width = "100%",
style = "color: #fff; background-color: #337ab7;
border-color: #2e6da4" )
)
server<-function(input, output, session){
observe({
cou_1<-input$cou_from
choice1<-c("", borders[grepl(paste0("^", cou_1), borders)])
updateSelectInput(session, "b_dir_1", choices=choice1)
})
observe({
bor_ch_1<-input$b_dir_1
choice2<-c("", borders[grepl(paste0("^", sub(".*-", "", bor_ch_1)), borders)])
updateSelectInput(session, "b_dir_2", choices=choice2)
})
}
shinyApp(ui = ui, server = server)
我希望 UI 看起来像这样:
【问题讨论】:
-
shinyjs包有方便的show和hide函数。