2

当使用 SelectInput 选择输入的可编辑 DataTable(包 DT)时,所做的编辑不会保存在应有的位置。

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

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

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

#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)
4

1 回答 1

2

试试这个:

#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)
于 2019-07-17T14:32:10.477 回答