Shiny R封装DT/Box组件时报closure对象不可子集化如何解决
问题根因
报错Error in $: object of type 'closure' is not subsettable的核心原因是对reactiveValues的用法错误:reactiveValues是Shiny提供的用于构造响应式变量容器的函数本身,你没有将其实例化赋值给自定义变量,直接对函数(闭包类型)使用$取子集操作,自然触发该报错。
修复方案
完全保留你现有的三个自定义函数封装结构,仅修改服务端逻辑的两处即可:
- 将
reactiveValues构造的响应式容器赋值给一个自定义变量(示例中命名为rv) - 调用响应式数据集时,使用实例化后的变量取子集,同时在渲染DT时补充
renderDT包裹(DT对象需要显式服务端渲染才能在UI中正常展示)
完整可运行修正代码
library(shiny) library(shinydashboard) library(DT) Create_DT <- function(dataSource){ datatable( dataSource, rownames = FALSE, selection = 'none', class = 'cell-border stripe', extensions = 'Buttons', options = list( buttons = list('copy', 'print', list(extend = 'collection',buttons = c('csv', 'excel', 'pdf'),text = 'Download')), dom = 'Bfrtip', info = FALSE, lengthChange = FALSE, paging = FALSE, searching = FALSE, scrollX = TRUE, columnDefs = list(list(className = 'dt-center', targets = "_all")) ) ) %>% formatStyle(colnames(dataSource),"white-space"="nowrap") } Create_Box <- function(description, collapsed, ui){ box( width = 12, title = strong(description), color = "primary", collapsible = TRUE, collapsed = collapsed, ui ) } Create_DTinBox <- function(description, collapsed, ui){ Create_Box(description, collapsed, ui) } ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( uiOutput("result") ) ) server <- function(input, output){ # 实例化响应式变量容器 rv <- reactiveValues(iris = iris) output$result <- renderUI({ Create_DTinBox( description = "test", collapsed = TRUE, ui = column(6, offset = 3, renderDT(Create_DT(rv$iris))) ) }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者tomsu
相关产品推荐
相关产品推荐

