You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny动态生成数值输入添加提交按钮延迟更新总和报错求助

Hey there! Let's fix up your Shiny app step by step. The error you're seeing comes from using <<- incorrectly in those nested lapply calls to populate your matrix, and we'll also sort out where to put the action button and how to make the sum update only when you click it.

Fixed Full Code

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel(title = "Use of action/submit button for multiple inputs"),
  sidebarLayout(
    sidebarPanel(
      numericInput("rows","Input No. of rows",value = 3,min=1),
      br(),
      numericInput("col","Input No. of cols",value = 1,min=1),
      br(),
      # Place the action button here in the fixed sidebar for easy access
      actionButton("calc_sum", "Calculate Total Sum")
    ),
    mainPanel(
      textOutput("display"),
      uiOutput("plo")
    )
  ))
)

server <- function(input,output){
  # Keep dynamic input generation as is - this part works fine
  output$plo <- renderUI({
    z <- input$col
    lapply(seq(input$col), function(j){
      column(width=3,
             lapply(seq(input$rows),function(i){
               numericInput(
                 inputId = paste0("range",i,j), # Simplified ID concatenation
                 label = paste("Input", i, ",", j), # Clearer label showing row/col
                 value = i*10 + j # Distinct initial value for easy identification
               )
             })
      )
    })
  })
  
  # Use eventReactive to only update matrix when button is clicked
  cm <- eventReactive(input$calc_sum, {
    c <- input$col
    r <- input$rows
    changed_m <- matrix(nrow = r, ncol = c)
    
    # Replace <<- with safe nested loops to populate matrix
    for(j in seq(c)){
      for(i in seq(r)){
        input_id <- paste0("range",i,j)
        changed_m[i,j] <- as.numeric(input[[input_id]]) # Ensure numeric type
      }
    }
    changed_m
  }, ignoreNULL = FALSE) # Ensure initial calculation on app load
  
  # Display sum only when cm() updates (on button click)
  output$display <- renderText({
    paste0("Sum of matrix: ", sum(cm(), na.rm = TRUE)) # Handle empty inputs safely
  })
}

shinyApp(ui, server)

Key Fixes & Explanations

  • Button Placement: I added the actionButton to the sidebarPanel—this is a fixed UI area, so it doesn't need to be part of the dynamic renderUI content. Users will see it immediately and know where to trigger the sum update. You could also place it in the mainPanel above the sum display if you prefer.
  • Removed <<-: The original error came from misusing <<- to modify the matrix in nested lapply calls. This caused environment variable conflicts and length mismatches. Replacing it with explicit for loops makes the matrix population safe and easy to follow.
  • Delayed Update with eventReactive: Instead of a regular reactive that updates on every input change, eventReactive only runs when the calc_sum button is clicked. The ignoreNULL = FALSE parameter ensures the initial sum loads when the app starts, without requiring a first button click.
  • Small Quality-of-Life Tweaks: I simplified input IDs, made labels clearer to show which row/col each input belongs to, and added na.rm = TRUE to the sum calculation to avoid errors if any input is left empty.

内容的提问来源于stack exchange,提问作者joy_1379

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:29:19