使用Shiny中的DT表进行可编辑的计算 [英] Editable calculation with DT table in Shiny

查看:47
本文介绍了使用Shiny中的DT表进行可编辑的计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一段时间了,已经阅读了一堆,但是我仍然不知道如何进行这项工作.有一个简单的解决方案吗?

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?

我想在我的 shiny 应用程序中编辑 DT 表,并且在编辑后,我希望对汇总两个值的列进行更改.

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.

这里是一个例子:

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值,并将更改反映在sum total列中.有一个简单的解决方案吗?

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?

推荐答案

您需要在 ObserveEvent 中使用如下所示的 _cell_edit .

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)

这篇关于使用Shiny中的DT表进行可编辑的计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆