datatable - 已编辑的 DataTable 未在 Shiny 模块中更新
问题描述
我想在数据表中嵌入 numericInput 和 checkBoxInput。我有一个 Xie Yihui 的例子,效果很好。和我想要的完全一样。但是当代码被包装在一个模块中时,编辑后的表不会更新。我读到这可能是由于命名空间,但我不知道如何解决它。
以下是要点:
提前致谢 :)
解决方案
只有一个小修复,如果您不熟悉 Shiny 模块,当然很难看出这一点。您在 Module Server 函数中创建的每个Input ID都必须包含在ns
其中(就像您在 UI 中所做的那样),但该函数隐藏在session$ns
服务器函数中。因此,在创建输入的第 18 行,它们的 ID 必须使用session$ns
. 从
inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
至
inputs[i] = as.character(FUN(paste0(session$ns(id), i), label = NULL, ...))
完整代码:
library(shiny)
library(DT)
editTableUI <- function(id) {
ns <- NS(id)
tagList(
DT::dataTableOutput(ns('x1')),
verbatimTextOutput(ns('x2'))
)
}
editTable <- function(input, output, session) {
# create a character vector of shiny inputs
shinyInput = function(FUN, len, id, ...) {
inputs = character(len)
for (i in seq_len(len)) {
inputs[i] = as.character(FUN(paste0(session$ns(id), i), label = NULL, ...))
}
inputs
}
# obtain the values of inputs
shinyValue = function(id, len) {
unlist(lapply(seq_len(len), function(i) {
value = input[[paste0(id, i)]]
if (is.null(value)) NA else value
}))
}
# a sample data frame
res = data.frame(
v1 = shinyInput(numericInput, 100, 'v1_', value = 0),
v2 = shinyInput(checkboxInput, 100, 'v2_', value = TRUE),
v3 = rnorm(100),
v4 = sample(LETTERS, 100, TRUE),
stringsAsFactors = FALSE
)
# render the table containing shiny inputs
output$x1 = DT::renderDataTable(
res, server = FALSE, escape = FALSE, options = list(
preDrawCallback = JS('function() {
Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() {
Shiny.bindAll(this.api().table().node()); } ')
)
)
# print the values of inputs
output$x2 = renderPrint({
data.frame(v1 = shinyValue('v1_', 100), v2 = shinyValue('v2_', 100))
})
}
shinyApp(
ui = fluidPage(
editTableUI("test")
),
server = function(input, output) {
callModule(editTable, "test")
}
)
推荐阅读
- vagrant - Vagrant 磁盘分区与 Debian 文件系统不匹配(分区较大)
- perl - 从模式到 TSV 的 Json
- git - 尽管文件夹发生了变化,git 不允许我推送文件
- java - 制作自定义 JTableModel 以监听 ArrayList 中的变化
- asp.net-mvc - 如何将 mvc 页面用作 Angular 5 templateUrl
- bluetooth - UART模块和运算
- javascript - 更改 javascript 中的 HTML 按钮颜色
- javascript - 没有值的 JavaScript 对象属性不显示
- excel - 将值重复到下一列
- javascript - 无法理解 async/await nodejs