R语言如何为双向扩展的矩阵创建动态索引
问题根源
报错的核心原因是空列判断逻辑错误:原代码中用sapply直接处理矩阵,会遍历矩阵的每一个元素,得到的逻辑向量长度等于矩阵总元素数,和矩阵列数不匹配,用来做列索引时就会触发「逻辑下标过长」的错误,极端情况会导致程序无响应。
修复方案
仅需修改observeEvent中的空列判断逻辑,将sapply改为按列遍历的apply即可:
server <- function(input, output, session) { sanitizedMat <- reactiveVal() # < 用于支持矩阵纵向扩展 observeEvent(input$myMatrixInput, { if(any(colnames(input$myMatrixInput) == "")){ tmpMatrix <- input$myMatrixInput # 把原来的sapply改成按列处理的apply empty_columns <- apply(tmpMatrix, 2, function(col) all(is.na(col) | col == "")) tmpMatrix <- tmpMatrix[, !empty_columns, drop = FALSE] colnames(tmpMatrix) <- paste("Scenario", rep(1:ncol(tmpMatrix), each = 2, length.out = ncol(tmpMatrix))) isolate(updateMatrixInput(session, inputId = "myMatrixInput", value = tmpMatrix)) } sanitizedMat(na.omit(input$myMatrixInput)) }) plotData <- reactive({ tryCatch( lapply(seq_len(ncol(sanitizedMat())/2), function(i){ tibble( Scenario = colnames(sanitizedMat())[i*2-1], X = seq_len(input$periods), Y = interpol(input$periods, sanitizedMat()[,(i*2-1):(i*2), drop = FALSE]) ) }) %>% bind_rows(), error = function(e) NULL ) }) output$plot <- renderPlot({ req(plotData()) plotData() %>% ggplot() + geom_line(aes( x = X, y = Y, colour = as.factor(Scenario) )) + theme(legend.title=element_blank()) }) }
修改后可正常支持矩阵横向新增场景、纵向新增数值点的双向扩展,插值、绘图功能均正常运行。
内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072
相关产品推荐
相关产品推荐

