Shiny中点击actionButton实现数据框行绑定更新table2的问题
问题分析
你当前的eventReactive(input$clip)每次触发时,仅返回本次读取的新数据——bind_rows()未传入之前的数据集,自然无法实现累积追加。要保留历史数据并实现更新,需要用reactiveValues来持久化存储累积的数据集。
解决方案
核心思路是用响应式对象存储累积数据,每次点击按钮时将新读取的数据追加进去:
修改后的核心代码段
# 创建响应式对象存储累积数据和计数器 accumulated_data <- reactiveValues(df = data.frame()) exp_counter <- reactiveValues(value = 0) observeEvent(input$clip, { exp_counter$value <- exp_counter$value + 1 # 读取剪贴板数据并添加exp标记 new_data <- read_clip_tbl() %>% mutate(exp = exp_counter$value) # 追加到累积数据中 accumulated_data$df <- bind_rows(accumulated_data$df, new_data) }) # 渲染table2 output$table2 <- renderTable({ req(accumulated_data$df) accumulated_data$df })
完整修改后代码
library(shiny) library(dplyr) library(shinydashboard) library(clipr) ui <- dashboardPage( dashboardHeader(), dashboardSidebar( actionButton('clip', 'Copy from clipboard'), actionButton("go", "Go") ), dashboardBody( tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ), plotOutput('plot1'), tableOutput( 'table1'), tableOutput( 'table2') ) ) server <- function(input, output, session) { # 响应式对象:存储累积的table2数据 accumulated_data <- reactiveValues(df = data.frame()) # 响应式计数器:标记每次剪贴板读取的批次 exp_counter <- reactiveValues(value = 0) observeEvent(input$clip, { exp_counter$value <- exp_counter$value + 1 # 读取剪贴板数据并添加批次标记 new_data <- read_clip_tbl() %>% mutate(exp = exp_counter$value) # 将新数据追加到累积数据集 accumulated_data$df <- bind_rows(accumulated_data$df, new_data) }) plot1 <- eventReactive(input$go, { read_clip_tbl() %>% mutate(treatment.name = as.factor(treatment.name)) %>% mort(plot_only=T) }) table1 <- eventReactive(input$go, { read_clip_tbl() %>% mutate(treatment.name = as.factor(treatment.name)) %>% mort(table_only=T) }) output$table2 <- renderTable({ req(accumulated_data$df) accumulated_data$df }) output$plot1 <- renderPlot({ req(plot1()) plot1() }) output$table1 <- renderTable({ req(table1()) table1() }) } shinyApp(ui, server)
关键修改点
- 用
accumulated_data$df持久化存储所有读取过的数据,替代原来每次生成临时数据的eventReactive - 新增
exp_counter确保每次点击clip按钮时,exp列能正确标记批次 - 在
observeEvent(input$clip)中完成读取新数据→添加标记→追加到累积数据的完整流程
内容的提问来源于stack exchange,提问作者scott.pilgrim.vs.r
相关产品推荐
相关产品推荐

