Shiny应用点击actionButton添加行正常删除行失效如何解决
问题根因
你代码点击删除按钮崩溃的核心是reactiveVal响应式变量的赋值语法错误:
reactiveVal类型变量的取值操作为变量名(),赋值操作需要将新值传入括号,写作变量名(新值),不能使用<-直接给变量名()赋值。你删除行逻辑中的data() <- data()[-as.numeric(input$TBL1_rows_selected),]不符合语法规则,触发程序崩溃。
你新增行的逻辑通过管道实现赋值虽然可以正常运行,但可读性较差,建议统一为标准写法更便于后续维护。
修复后完整可运行代码
library(shiny) library(shinydashboard) library(shinydashboardPlus) library(DT) library(tibble) Input <- structure(list(`Security Type` = c("Stock", "Stock", "Load Fund"), Ticker = c("XOM", "NFLX", "AMCPX"), `Purchase Date` = structure(c( 16070, 17084, 17084 ), class = "Date"), `Sale Date` = structure(c( 18627, NA, 18545 ), class = "Date"), `Amount Invested` = c( "$10,000", "$8,000", "$10,000" )), class = c( "spec_tbl_df", "tbl_df", "tbl", "data.frame" ), row.names = c(NA, -3L)) shinyApp( ui = tags$body(class = "skin-blue sidebar-mini control-sidebar-open", dashboardPage( options = list(sidebarExpandOnHover = TRUE), header = dashboardHeader(title = "Investment Advisor Monitoring - Insider Trading", titleWidth = 450), sidebar = dashboardSidebar( minified = F, collapsed = F, selectInput( "sectype", "Security Type", c(unique(Input$`Security Type`)) ), selectInput( "sectick", "Ticker", c(unique(Input$Ticker)) ), dateInput("PurDate", "Purchase Date", value = as.Date("2013-12-31")), dateInput("selDate", "Sale Date", value = as.Date("2019-01-31")), selectInput( "aminv", "Amount Invested", c(unique(Input$`Amount Invested`)) ), actionButton("add", "Add"), actionButton("deleteRows", "Delete Rows") ), body = dashboardBody( h3("Results"), tabsetPanel( id = "tabs", tabPanel( "InsiderTraining", dataTableOutput("TBL1") ) ) ), controlbar = dashboardControlbar(width = 300), title = "DashboardPage" )), server = function(input, output) { # 初始化示例数据 data <- reactiveVal(Input) observeEvent(input$add, { # 读取当前数据新增行后更新响应式变量 new_data <- data() %>% add_row( `Security Type` = isolate(input$sectype), Ticker = isolate(input$sectick), `Purchase Date` = isolate(input$PurDate), `Sale Date` = isolate(input$selDate), `Amount Invested` = isolate(input$aminv) ) data(new_data) }) observeEvent(input$deleteRows,{ if (!is.null(input$TBL1_rows_selected)) { # 修正为reactiveVal标准赋值语法 data(data()[-as.numeric(input$TBL1_rows_selected), ]) } }) output$TBL1 <- renderDataTable( data(), selection = "single" ) } )
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

