我正在尝试渲染相同的UI n次,其中时间t的每个元素ui都依赖于前一个(t-1)。这是我的reprex在n = 2上工作的地方,其中我手动编写了renderUI:
library(shiny)
choices0 <- LETTERS[1:10]
ui <- fluidPage(
tagList(
checkboxGroupInput("cbGI_0", label = 0, inline = TRUE,
choices = choices0,
selected = choices0),
uiOutput("cbGI_ui_1")
)
)
server <- function(input, output) {
output$cbGI_ui_1 <- renderUI({
choices <- choices0[!choices0 %in% input$cbGI_0]
if (length(choices) > 0){
tagList(
checkboxGroupInput("cbGI_1", label = 1, inline = TRUE,
choices = choices,
selected = choices),
uiOutput("cbGI_ui_2")
)
}
})
output$cbGI_ui_2 <- renderUI({
choices <- choices0[!choices0 %in% c(input$cbGI_0, input$cbGI_1)]
if (length(choices) > 0){
tagList(
checkboxGroupInput("cbGI_2", label = 2, inline = TRUE,
choices = choices,
selected = choices),
uiOutput("cbGI_ui_3")
)
}
})
#and so on
}
shinyApp(ui = ui, server = server)
我的问题是关于做相同的事情,但时间不限。我尝试这样编码,但不起作用:
library(shiny)
choices0 <- LETTERS[1:10]
ui <- fluidPage(
tagList(
checkboxGroupInput("cbGI_0", label = 0, inline = TRUE,
choices = choices0,
selected = choices0),
uiOutput("cbGI_ui_1")
)
)
server <- function(input, output) {
n <- reactive({
length(sapply(names(input), grepl, pattern = "cbGI_[0-9]*$"))
})
observe({
for (i in seq_len(n())){
output[[paste0("cbGI_ui_", i)]] <- renderUI({
choices <- choices0[!choices0 %in%
sapply(seq_len(i), function(k){
input[[paste0("cbGI_", k-1)]]
})
]
if (length(choices) > 0){
tagList(
checkboxGroupInput(paste0("cbGI_", i), label = i, inline = TRUE,
choices = choices,
selected = choices),
uiOutput(paste0("cbGI_ui_", i+1))
)
}
})
}
})
}
shinyApp(ui = ui, server = server)
似乎我陷入了无限循环...知道如何解决我的问题吗?