Editable calculation with DT table in Shiny

天涯浪子 提交于 2021-01-29 08:47:50

问题


I've been at this for awhile and have read a bunch but I still can't wrap my head around how to make this work. Is there a simple solution?

I want to edit a DT table in my shiny app and, upon editing, I'd like there to be a change in a column that aggregates two values.

Here is an example:

library(tidyverse)
library(shiny)
library(DT)

mt <- mtcars %>%
    select(mpg, cyl) %>%
    head()

ui <- fluidPage(
  
  DTOutput(outputId = "final_tbl")
)

server <- function(input, output){

  dat <- reactive({
    d <- mt %>%
      mutate(total = mpg + cyl)
    d
  })
    
  output$final_tbl <- renderDT({
    
    dat() %>%
      datatable(editable = TRUE)
    
  })
}

shinyApp(ui, server)

This produces a simple editable table with a total column that adds up mpg and cyl. What I'd like to be able to do is edit the cyl value and have the change reflected in the summed total column. Is there an easy solution to this?


回答1:


You need to use _cell_edit as shown below in a ObserveEvent.

mt <- mtcars %>%
  select(mpg, cyl) %>%
  head()

ui <- fluidPage(
  
  DTOutput(outputId = "final_tbl")
)

server <- function(input, output){
  df1 <- reactiveValues(data=NULL)
  dat <- reactive({
    d <- mt %>%
      mutate(total = mpg + cyl)
    d
  })
  
  observe({
    df1$data <- dat()
  })
  
  output$final_tbl <- renderDT({
    
    df1$data %>%
      datatable(editable = TRUE)
    
  })
  
  observeEvent(input$final_tbl_cell_edit, {
    info = input$final_tbl_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    
    # Without this line the table does not change but with it it jumps to row 1 after an edit.
    df1$data[i, j] <<- (DT::coerceValue(v, df1$data[i, j]))
    df1$data[,"total"] <<- df1$data[,"mpg"] + df1$data[,"cyl"]  ## update the total column
  })

}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/64997096/editable-calculation-with-dt-table-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!