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

R Shiny可扩展输入矩阵重新渲染时如何保留已输入的数值?

问题根因

每次点击按钮弹出模态框时,代码都会重新调用secondInput生成仅含2列的新矩阵,仅保留了原input2的第二列数值,新增列的所有数据都没有被继承,因此关闭模态框再打开后新增列数值丢失,同时冗余的output$secondInput渲染逻辑未绑定UI,还可能造成输入冲突。

修复后完整代码
library(shiny)
library(shinyMatrix)

yDflt <- 5

firstInput <- function(inputId,y,z){ # << y = y col default value, z = matrix row label
  matrixInput(inputId, 
              value = matrix(c(10,y), 1, 2, dimnames = list(c(z),c("X and Y",""))),
              rows =  list(extend = FALSE, names = TRUE),
              cols =  list(
                extend = FALSE, 
                names = TRUE, 
                editableNames = FALSE,
                multiheader=TRUE
              ),
              class = "numeric")}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      uiOutput("panel"),
      actionButton("showSecond","Show 2nd input (modal)",width = "100%")
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server <- function(input, output, session){
 
  output$panel <- renderUI({firstInput("input1",yDflt,"1st input")})
  
  observeEvent(input$showSecond,{
    # 优先使用已有的完整input2矩阵,未初始化则从input1取初始值
    init_mat <- if(isTruthy(input$input2)) {
      input$input2
    } else {
      matrix(c(10, input$input1[1,2]), 1, 2, dimnames = list(c("2nd input"),c(1,"")))
    }
    showModal(
      modalDialog(
        matrixInput("input2", 
                    value = init_mat,
                    label = "Add, delete, or modify matrix parameters:",
                    rows =  list(extend = FALSE, names = TRUE),
                    cols =  list(
                      extend = TRUE,
                      delta = 2,
                      delete = TRUE,
                      names = TRUE, 
                      editableNames = FALSE,
                      multiheader=TRUE
                    ),
                    class = "numeric"),
        footer = modalButton("Close")
      ))
  })
  
  observe({ # << Assign sequential col header to matrix based on groupings of two
    req(input$input2)
    mm <- input$input2
    colnames(mm) <- trunc(1:ncol(mm)/2)+1 
    isolate(updateMatrixInput(session, "input2", mm))
  })
  
  output$plot1 <-renderPlot({
    req(input$input1)
    plot(rep(if(isTruthy(input$input2)){input$input2[1,2]} else {input$input1[1,2]}, times=10))
  })
  
}

shinyApp(ui, server)
核心修改点
  • 弹出模态框时不再重新生成固定2列的新矩阵,而是优先传入已存在的完整input2矩阵作为初始值,保留所有新增列的数值
  • 删除了未绑定UI、冗余的output$secondInput渲染逻辑,避免输入冲突

内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:39:02