R Shiny可编辑响应式表格点击按钮调用agree()计算报错如何解决
问题修复方案
错误根源
你的问题由3处核心逻辑错误导致:
- 输出对象定义逻辑冲突:
renderPrint是Shiny的输出渲染函数,不能嵌套在eventReactive中给output$irr1赋值,二者功能不兼容是报错的直接原因 - 数据源引用错误:你直接使用
table1作为agree()的入参,但table1是UI端DT组件的输出ID,不是存储数据的变量,实际表格数据存在tablevalues$df中 - 缺少可编辑表格数据同步逻辑:默认DT编辑操作不会自动更新你定义的
reactiveValues,修改后的表格内容不会同步到tablevalues$df
修复后完整代码
library(shiny) library(irr) library(DT) library(dplyr) library(shinydashboard) ui <- dashboardPage( dashboardHeader(title = "Interview Reliability"), dashboardSidebar( sidebarMenu( menuItem("Two Interviewers", tabName = "2int", icon = icon("glass-whiskey")), menuItem("Three Interviewers", tabName = "3int", icon = icon("glass-whiskey")), menuItem("Four Interviewers", tabName = "4int", icon = icon("glass-whiskey")) ) ), dashboardBody( tabItems( tabItem(tabName = "2int", fluidRow(box(sliderInput("obs1", "Number of Interview Questions:", value = 4, min = 4, max = 12, step = 1))), box(dataTableOutput("table1")), box(verbatimTextOutput("irr1")), box(actionButton("calc1", "Calculate")) ), tabItem(tabName = "3int", box(sliderInput("obs2", "Number of Interview Questions:", value = 4, min = 4, max = 12, step = 1)) ), tabItem(tabName = "4int", box(sliderInput("obs3", "Number of Interview Questions:", value = 4, min = 4, max = 12, step = 1)), ) ) ) ) server <- function(input, output) { tablevalues <- reactiveValues(df = NULL) # 初始化表格,直接定义为整数类型适配后续统计函数要求 observeEvent(input$obs1, { tablevalues$df <- matrix(NA_integer_, nrow = input$obs1, ncol = 2, dimnames = list(1:input$obs1, c("Interviewer 1", "Interviewer 2"))) }) # 渲染可编辑DT output$table1 <- renderDT(tablevalues$df, escape = FALSE, selection = 'none', editable=TRUE) # 新增:同步DT编辑内容到reactiveValues,自动转换为整数类型 observeEvent(input$table1_cell_edit, { edit_info <- input$table1_cell_edit tablevalues$df[edit_info$row, edit_info$col] <- as.integer(edit_info$value) }) # 修复irr1输出逻辑 output$irr1 <- renderPrint({ # 点击计算按钮后才触发 req(input$calc1) # 确保表格无缺失值再计算,避免报错 req(complete.cases(tablevalues$df)) # 转换为数据框后传入计算,可替换为cor()做功能测试 agree(as.data.frame(tablevalues$df)) # 测试用代码:cor(as.data.frame(tablevalues$df)) }) } shinyApp(ui = ui, server = server)
功能验证说明
- 拖动滑块调整题目数量后会自动生成对应行数的空表格
- 双击表格单元格可输入数值,编辑内容会自动同步到后台变量
- 填写完全部数值后点击
Calculate按钮即可输出统计结果
内容的提问来源于stack exchange,提问作者Sam_Donnelly
相关产品推荐
相关产品推荐

