【发布时间】:2020-05-22 14:01:31
【问题描述】:
我的 Shiny 应用加载的数据在使用前必须经过验证和更正。
但我无法坚持更改。例如,在 MWE 中,将梨的数量从 18 更改为 12 不会更新 data.dt 中的 data.table。
编辑如何保留并传播到第二个选项卡?
MWE:
## Load libraries
library(data.table)
library(shiny)
library(DT)
## Simulate loaded data
indata.dt <- data.table(Category=c("Fruits", "Fruits", "Fruits", "Vegetables", "Vegetables"),
Item=c("Apple", "Pear", "Orange", "Cucumber", "Tomato"),
Count=c(17L, 18L, 23L, 5L, 8L))
## UI
ui <- fluidPage(
titlePanel("GreensApp"),
tabsetPanel(type = "tabs",
tabPanel("Define Items",
sidebarLayout(
sidebarPanel(
selectInput(inputId="selectedCategory", label="Choose a category:",
choices=sort(unique(indata.dt$Category)),
multiple=FALSE
)
),
mainPanel(
DT::dataTableOutput("table1")
)
)
),
tabPanel("See the updated table",
DT::dataTableOutput("table2")
)
)
)
## Server
server <- function(input, output) {
filterData <- reactive({
indata.dt[Category==input$selectedCategory, list(Item, Count)]
})
output$table1 <- DT::renderDataTable({
DT::datatable(filterData(), selection="single", rownames=FALSE, editable=list(target="cell"))
})
output$table2 <- DT::renderDataTable({
DT::datatable(filterData(), selection="single", rownames=FALSE)
})
observeEvent(input$table1_cell_edit, {
cell <- input$table1_cell_edit
indata.dt[cell$row, cell$col] <- cell$value
})
}
# Run
shinyApp(ui = ui, server = server)
可以通过编辑水果计数、选择蔬菜然后再次选择水果来观察问题。新的计数恢复到原来的值。
【问题讨论】: