如何在闪亮的服务器功能中复制反应值

how to make a copy of a reactive value in shiny server function

我正在构建一个闪亮的应用程序并使用这个问题的代码作为示例:。但是,在我的代码中 df <- reactiveVal(dat) 不起作用,因为 dat 本身已经是来自 eventReactive({}) 函数的反应值。这是我正在使用的代码,如果我在服务器外部定义 dat 它会起作用,但在闪亮的服务器函数内部创建时则不起作用。我如何复制它以便我可以在新的 table 中显示它(并可能进一步处理并在应用程序的后续步骤中下载)?

library(shiny)
library(DT)
library(shinyWidgets)


# if the data frame is just an object, it works
#dat <- iris[1:3, ]

ui <- fluidPage( actionBttn(
  inputId = "btnProcess",
  label = "Process",
  size = "sm",
  color = "success"
),
  DTOutput("my_table"),
  DTOutput("table2")
  
)

server <- function(input, output){
  
  
  # if the dataframe is a reactive variable, this doesnt work.
  dat <- eventReactive(input$btnProcess, {
    iris[1:3, ]
  })
  
  
  output[["my_table"]] <- renderDT({
    datatable(dat(), editable = "cell")
  })
  
  
  #############################
  #### none of these work #####
  #############################
  
  #df <- reactiveVal(dat)
  #df <- reactiveVal(dat())
  #df <- dat()
  #df <- dat
  
  
  observeEvent(input[["my_table_cell_edit"]], {
    cell <- input[["my_table_cell_edit"]]
    newdf <- df()
    newdf[cell$row, cell$col] <- cell$value
    df(newdf)
  })
  
  
  output[["table2"]] <- renderDT({
    datatable(df())
  })
  
  
}

shinyApp(ui, server)

试试这个

ui <- fluidPage( actionBttn(
  inputId = "btnProcess",
  label = "Process",
  size = "sm",
  color = "success"
), 
actionBttn(inputId = "reset", label = "Reset", size="sm", color="warning"),
DTOutput("mytable"),
DTOutput("table2")

)

server <- function(input, output){
  
  
  # if the dataframe is a reactive variable, this doesnt work.
  dat <- eventReactive(input$btnProcess, {
    iris[1:3, ]
  })
  
  mydf <- reactiveValues(data=NULL)
  
  observe({
    mydf$data <- dat()
  })
  
  output$mytable <- renderDT({
    datatable(mydf$data, editable = "cell")
  })
  
  observeEvent(input$mytable_cell_edit, {
    info = input$mytable_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    
    mydf$data[i, j] <<- DT::coerceValue(v, mydf$data[i, j])
    
  })
  
  output[["table2"]] <- renderDT({
    datatable(mydf$data)
  })
  
  observeEvent(input$reset, {
    mydf$data <- dat()   ## reset it to original data
  })
  
}

shinyApp(ui, server)