繁体   English   中英

在 Shiny 中使用 DT 表进行可编辑的计算

[英]Editable calculation with DT table in Shiny

我已经在这方面工作了一段时间并阅读了大量内容,但我仍然无法理解如何使这项工作发挥作用。 有简单的解决方案吗?

我想在我shiny应用程序中编辑一个DT表,并且在编辑时,我希望聚合两个值的列发生变化。

下面是一个例子:

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)

这将生成一个简单的可编辑表格,其中总列将 mpg 和 cyl 相加。 我希望能够做的是编辑 cyl 值并将更改反映在总和列中。 有没有简单的解决方案?

你需要使用_cell_edit如在图所示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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM