动态 UI - 为动态创建的表创建 observeEvents

Dynamic UI - Creating observeEvents for Dynamically Created Tables

试图了解如何创建 observeEvent() 以捕获对任意数量的动态创建的 RHandson 表的更改。有人成功过吗?

下面的代码显示了动态表的创建。底部的注释表示我想跟踪的输入,但 observeEvents 需要考虑一组任意的输入名称。

library(shiny)
library(dplyr)
library(rhandsontable)
library(purrr)
ui <- fluidPage(

  uiOutput('tables')
)

server <- function(input, output) {
  mtcars$slc <- sample(c('aaa','bbb'),nrow(mtcars),replace=TRUE)
  df <- mtcars
  
  getSlice <- function(df_tmp,slca){
    print(slca)
    df_tmp <- df_tmp %>% filter(slc==slca)
    df_tmp
  }
  
  output$tables <- renderUI({
    slices <- unique(df$slc)
    input_dfs <- map(slices,~getSlice(df,.x))
    
    for(i in 1:length(slices)){
      local({
        i <- i
        print(input_dfs[[i]])
        output[[slices[i]]] <- renderRHandsontable(rhandsontable(input_dfs[[i]]))
      })
    }
    
    out <- map(slices,function(x){
      rHandsontableOutput(x)
    })
    print(out)
    out
  })
  
  ### How do I create observeEvents for...
  # input$aaa$changes$changes
  # input$bbb$changes$changes
  # input$arbitrarySlice$changes$changes
  
}

shinyApp(ui = ui, server = server)

您可以使用 lapply() 迭代添加 observeEvents,如下所示:

library(shiny)
library(dplyr)
library(rhandsontable)
library(purrr)
ui <- fluidPage(
    uiOutput("tables")
)

server <- function(input, output) {
    mtcars$slc <- sample(c("aaa", "bbb"), nrow(mtcars), replace = TRUE)
    df <- mtcars

    getSlice <- function(df_tmp, slca) {
        print(slca)
        df_tmp <- df_tmp %>% filter(slc == slca)
        df_tmp
    }

    output$tables <- renderUI({
        slices <- unique(df$slc)
        input_dfs <- map(slices, ~ getSlice(df, .x))

        for (i in 1:length(slices)) {
            local({
                i <- i
                print(input_dfs[[i]])
                output[[slices[i]]] <- renderRHandsontable(rhandsontable(input_dfs[[i]]))
            })
        }
        out <- map(slices, function(x) {
            rHandsontableOutput(x)
        })
        print(out)
        out
    })

    ### How do I create observeEvents for...
    # input$aaa$changes$changes
    # input$bbb$changes$changes
    # input$arbitrarySlice$changes$changes

    ### Iteratively add observeEvent()
    lapply(unique(df$slc), function(slice) {
        observeEvent(input[[slice]]$changes$changes, {
            print(paste(slice, "has been updated!"))
            print(input[[slice]][["changes"]])
        })
    })

}

shinyApp(ui = ui, server = server)