Shiny应用报错Error in $: 'closure'类型对象不可子集化求解
错误原因
你遇到的报错是因为变量命名冲突:
- 你在全局环境预先定义了名为
Targets2的数据集对象 - 在server中你又定义了同名的reactive响应式对象
Targets2,在reactive的内部代码执行时,R会优先找到当前作用域下刚定义的这个reactive对象,而reactive本质是closure类型的函数,无法使用$操作符取列,因此抛出了对应错误。
解决方案
最简单的修复方案是将reactive对象的名字改为和全局数据集不同的名称,避免作用域覆盖,示例修改后的完整server代码如下:
server <- function(input, output) { # 修改响应式对象命名,避免和全局数据集重名 filtered_Targets2 <- reactive({ subset(Targets2, Targets2$Week %in% input$weeks) }) output$plot<-renderPlotly({ p <- ggplot(filtered_Targets2(), aes(x = Week, y = Count, fill = Type))+ geom_area(alpha = 0.6 , size = 0.5, colour = "white", stat = "identity", orientation = "x") + theme_ipsum() + theme(legend.position = "bottom") p <- p+labs(title = "Figure 1: Weekly Cumulative Projected Enrollment vs Weekly Cumulative Actual Enrollment", subtitle = "Cum Weekly Projected Enrollment/Cum Weekly Actual Enrollment") ggplotly(p) }) }
如果你确实需要保留响应式对象的命名为Targets2,也可以在subset调用时明确指定取全局环境的原始数据集:
Targets2 <- reactive({ subset(globalenv()$Targets2, Week %in% input$weeks) })
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

