如何在正确位置使用 SelectInput 时保存在 DT 中所做的编辑

How to save edits made in DT while using SelectInput in correct position

当使用由 SelectInput 选择输入的可编辑数据表(包 DT)时,所做的编辑未保存在应有的位置。

选择特定变量会在第一行显示数据表中的第 50-60 行。编辑它们会将编辑保存在第一行而不是第 50-60 行。

在下面的示例中,您可以选择变量 versicolor 并删除 setosa。然后编辑 Petal.Length 为随机数。编辑应该保存在第 51 行,但它保存在第 1 行。

我正在考虑基于索引列的解决方法,以便将编辑内容保存在行号 (indexrow) 中。但我不知道该怎么做。

#Packages
library(shiny)
library(shinyalert)
library(shinydashboard)
library(leaflet)
library(leaflet.extras)
library(DT)

#data
iris = iris

#Shiny-app (ui)
header = dashboardHeader(title = "SelectInput DataTable example")

sidebar = dashboardSidebar(selectInput("species", "Choose species:  ",    choices = iris$Species, selected = "setosa",  multiple = TRUE))

body = dashboardBody(fluidRow(dataTableOutput("table")))

ui = dashboardPage(skin = "red", header, sidebar, body)

#Server
server <- function(input, output, session) {


  output$table = DT::renderDataTable(iris[iris$Species %in% input$species,], editable = TRUE)

  proxy = dataTableProxy('table')

  observeEvent(input$table_cell_edit, {
    info = input$table_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    iris[i, j] <<- DT::coerceValue(v, iris[i, j])
    replaceData(proxy, iris, resetPaging = FALSE)  # important
  })
}

shinyApp(ui = ui, server = server)

试试这个:

#Packages
library(shiny)
library(shinydashboard)
library(DT)

#data
iris = iris

#Shiny-app (ui)
header = dashboardHeader(title = "SelectInput DataTable example")

sidebar = dashboardSidebar(selectInput("species", "Choose species: ", 
                                       choices = iris$Species, selected = "setosa",  multiple = TRUE))

body = dashboardBody(fluidRow(DT::dataTableOutput("table")))

ui = dashboardPage(skin = "red", header, sidebar, body)

# Javascript 
js <- function(rows){
  c(
    "function(settings){",
    "  var table = settings.oInstance.api();",
    sprintf("  var indices = [%s];", paste0(rows-1, collapse = ",")),
    "  table.rows(indices).remove().draw();",
    "}"
  )
}

#Server
server <- function(input, output, session) {

  dat <- reactiveVal(iris)

  Rows <- reactive({
    which(iris$Species %in% input$species)
  })

  output$table = DT::renderDataTable({
    rows <- setdiff(1:nrow(iris), Rows())
    datatable(
      dat(), 
      editable = TRUE,
      options = list(
        initComplete = JS(js(rows))
      )
    )
  }, server = FALSE)

  observeEvent(input$table_cell_edit, {
    info = input$table_cell_edit
    info$row = Rows()[info$row+1] - 1
    dat(editData(dat(), info))
  })
}

shinyApp(ui = ui, server = server)