【发布时间】:2020-09-14 22:49:12
【问题描述】:
下面的小应用程序生成一个 DT::datatable,其中包含两列 x,y。 X 开始是一个带有 rnorm 的随机数。 y 应该是 x 加 1 的任何值。
该应用允许用户编辑 DT::datatable 中的 x 列。我已经构建了它,以便用户可以修改 x 列,但是,y 列没有按预期更新,它只是保持不变。
闪亮的代码:
library(shiny)
library(tidyverse)
library(shinydashboard)
library(scales)
library(DT)
# define functions
## generate example data
create_sample_df <- function(x) {
data.frame(
x = x %>% unlist
) %>% mutate(y = x + 1)
}
## render DT
render_dt = function(data, editable = 'cell', server = TRUE, ...) {
renderDT(data, selection = 'none', server = server, editable = editable, ...)
}
# UI ----
header <- dashboardHeader(title = 'blah')
sidebar <- dashboardSidebar()
body <- dashboardBody(DT::DTOutput('ex_df'))
ui <- dashboardPage(header, sidebar, body)
# Server ----
server <- function(input, output) {
x <- rnorm(10, 0, 2) %>% as.integer %>% as.list
# the df to be displayed as a DT::datatable.
ex_df <- reactive({create_sample_df(x)})
## set to initially be the on open result of ex_df, before any user input
reactivs <- reactiveValues(ex_df = ex_df)
observeEvent(input$ex_df_cell_edit, {
info = input$ex_df_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
# update budgets, which in turn is used to generate data during create_sample_df()
x[[i]] <<- v
# now update the reactive values object with the newly generated df
reactivs$ex_df <<- reactive({create_sample_df(x)})
})
output$ex_df <- render_dt(data = reactivs$ex_df(),
rownames = FALSE,
list(target = 'cell',
disable = list(columns = c(1))))
}
shinyApp(ui, server)
在屏幕上,我将 x 列中的第一行从 -1 编辑为 10。按回车后,期望的结果是第 1 行的 x 值为 10,y 值为 11。
目前这不会发生,无论如何 y 保持不变。此外,第一次尝试编辑 x 列不起作用,只有在第二次尝试后新值才会保留。
【问题讨论】: