简体   繁体   中英

Editable calculation with DT table from Upload File in Shiny

What I want to do is:

  1. I will upload the excel file to the shiny app
  2. Then I will display in the output the body shiny app where the table can be edited
  3. when I edit the table, the "total" field will be recalculated based on the value of the "bb" and "cc" fields

Where at this time I have not found a way to do point no 3, please help

library(shiny)
library(DT)
library(readxl)

server <- function(input, output, session){
  df1 <- reactiveValues(data=NULL)
  myData <- reactive({
      inFile <- input$TT
      if(is.null(inFile))
        return(NULL)
      file.rename(inFile$datapath,
                  paste(inFile$datapath, ".xlsx", sep=""))
      df_TT_raw <- read_excel(paste(inFile$datapath, ".xlsx", sep=""), 1)
      df_TT <- df_TT_raw %>% 
        mutate_if(is.numeric, round, digits=2) %>%
        mutate(total = bb + cc)
      df_TT
  })
  
  observe({
    df1$data <- myData()
  })
  
  output$contents <- DT::renderDataTable({
    
    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
    
    .
    df1$data[i, j] <<- (DT::coerceValue(v, df1$data[i, j]))
    df1$data[,"total"] <<- df1$data[,"bb"] + df1$data[,"cc"]  ## update the total column
  })

  
}


ui<- shinyUI(fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput(inputId = "TT",
                label = "Upload Test",
                accept = c(".xlsx",".csv")
      )
    ),
    mainPanel(
      DT::dataTableOutput('contents')
    )
  )
)
)

shinyApp(ui,server)

You should assign the correct id for the output table you are editing, namely, contents . Also, please remove the . in the observeEvent as shown below. Try this

  observeEvent(input$contents_cell_edit, {
    info = input$contents_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = as.numeric(info$value)
    
    df1$data[i, j] <<- DT::coerceValue(v, df1$data[i, j])
    
    df1$data[,"total"] <<- df1$data[,"bb"] + df1$data[,"cc"]  ## update the total column
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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