【发布时间】:2021-06-03 20:04:04
【问题描述】:
我想创建动态数量的控件(使用renderUI)并让这些控件更新reactiveValues 对象。但是,当应用加载时,reactiveValues 对象似乎是 NULL,因此所有值都会更新为 NULL,而不是所需的初始状态。
library(shiny)
ui <- fluidPage(
uiOutput("controls"),
tableOutput("result")
)
server <- function(input, output) {
# Initial state of reactive values
rv <- reactiveValues(
my_table = dplyr::starwars %>%
select(name) %>%
mutate(checkbox = TRUE) %>%
sample_n(10)
)
# Render the dynamic UI
output$controls <- renderUI({
lapply(1:nrow(rv$my_table), function(i) {
fluidRow(
column(1, checkboxInput(paste0('checkbox',i), value = rv$my_table[[i,"checkbox"]], label = NULL)),
column(4, textInput(paste0('name',i), value = rv$my_table[[i,"name"]], label = NULL, width = '600'))
)
})
})
# Update state of reactive values
observe({
checkboxes <- unlist(lapply(1:nrow(rv$my_table), function(i) {
input[[paste0("checkbox", i)]]
}))
print(checkboxes) # It seems on load as NULL first before the rv$my_table loads
names <- unlist(lapply(1:nrow(rv$my_table), function(i) {
input[[paste0("name", i)]]
}))
# rv$my_table['checkbox'] <- checkboxes # Uncomment for desired updates
# rv$my_table$name <- names # Uncomment for desired updates
})
# Render output
output$result <- renderTable({
rv$my_table %>%
filter(checkbox)
})
}
shinyApp(ui = ui, server = server)
【问题讨论】:
标签: r shiny shiny-reactivity