【问题标题】:how to make a copy of a reactive value in shiny server function如何在闪亮的服务器功能中复制反应值
【发布时间】:2024-04-13 05:00:02
【问题描述】:

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

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)

【问题讨论】:

    标签: r shiny datatable


    【解决方案1】:

    试试这个

    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)
    

    【讨论】:

    • 如果我添加它并对代码进行任何更改,它仍然会出错
    • 比你好!我现在还有一个简短的后续问题,我为此开了一个新问题:*.com/questions/66333176/…