在R Shiny中如何仅更新用户输入矩阵中的单个指定值?
实现方案
完全可以保留Matrix 2除[1,2]位置外的所有历史输入,你当前的问题是更新matrix2时直接重写了整个矩阵,导致用户新增的行数据被覆盖,同时维度不匹配触发了控制台警告。
仅需修改server段中两个observeEvent的更新逻辑,只修改目标位置的值、保留其余原有数据即可,修改后的完整代码如下:
library(shiny) library(shinyMatrix) interpol <- function(a, b) { # [a] = modeled periods, [b] = matrix inputs c <- b c[,1][c[,1] > a] <- a d <- diff(c[,1, drop = FALSE]) d[d <= 0] <- NA d <- c(1,d) c <- cbind(c,d) c <- na.omit(c) c <- c[,-c(3),drop=FALSE] e <- rep(NA, a) e[c[,1]] <- c[,2] e[seq_len(min(c[,1])-1)] <- e[min(c[,1])] if(max(c[,1]) < a){e[seq(max(c[,1]) + 1, a, 1)] <- 0} e <- approx(seq_along(e)[!is.na(e)], e[!is.na(e)], seq_along(e))$y # Interpolates return(e) } ui <- fluidPage( sliderInput('periods', 'Modeled periods (X):', min=1, max=10, value=10), h5(strong("Matrix 1:")), matrixInput("matrix1", value = matrix(c(5), nrow = 1, ncol = 1, dimnames = list("Base rate (Y)",NULL)), rows = list(extend = FALSE, names = TRUE), cols = list(names = FALSE), class = "numeric"), h5(strong("Matrix 2:")), matrixInput("matrix2", value = matrix(c(10,5), nrow = 1, ncol = 2, dimnames = list(NULL,c("X","Y"))), rows = list(extend = TRUE, names = TRUE, delete = TRUE), class = "numeric"), plotOutput("plot") ) server <- function(input, output, session){ observeEvent(input$periods,{ # 先获取当前matrix2的全部数据,仅修改第一行第一列的X值 tmp_mat <- input$matrix2 tmp_mat[1, 1] <- input$periods updateMatrixInput( session, inputId = "matrix2", value = tmp_mat ) }) observeEvent(input$matrix1, { # 先获取当前matrix2的全部数据,仅修改第一行第二列的Y值 tmp_mat <- input$matrix2 tmp_mat[1, 2] <- input$matrix1[1, 1] updateMatrixInput( session, inputId = "matrix2", value = tmp_mat ) }) observeEvent(input$matrix2, { if(any(rownames(input$matrix2) == "")){ tmpMatrix <- input$matrix2 rownames(tmpMatrix) <- paste("Row", seq_len(nrow(input$matrix2))) isolate(updateMatrixInput(session, inputId = "matrix2", value = tmpMatrix)) } input$matrix2 }) output$plot <- renderPlot({ req(input$matrix2) plot(interpol(input$periods, input$matrix2)) }) } shinyApp(ui, server)
修改后触发滑块调整、Matrix1输入时,都只会修改Matrix2第一行对应位置的值,其余所有用户手动新增的行数据都会完整保留,同时控制台的维度不匹配警告也会消失。
问题相关截图



内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072
相关产品推荐
相关产品推荐

