【问题标题】:How to fix a matrix value when running updateMatrixInput function in R shiny?在 R Shiny 中运行 updateMatrixInput 函数时如何修复矩阵值?
【发布时间】:2023-03-19 09:42:01
【问题描述】:

下面的简单 MWE 代码反映了对 (a) 句点 (X) 的滑块输入和 (b) X 变量(句点,链接到其上方的滑块输入)和 Y 变量的矩阵输入的更改,在在主面板中绘制到右侧。 X = 60 和 Y = 0.20 的默认值。

工作正常,除了当矩阵输入中的 Y 变量从默认的 0.20 更改时,随后移动滑块输入会将 Y 变量重置回 0.20。我该如何解决这个问题,以便 Y 变量保持静态(保持更改后的值),而不是在移动输入滑块时恢复为默认值?

代码:

library(shiny);library(shinyMatrix);

matrix2.input <- function(x,y,z){
  matrixInput(
    x,
    value = matrix(c(y,z),1,2,dimnames=list(NULL,c("X","Y"))),
    rows = list(extend = FALSE,  names = FALSE),
    cols = list(extend = FALSE, names = TRUE, editableNames = FALSE),
    class = "numeric")} 

matrix.validate <- function(x,y){
  a <- x                                
  a[,1][a[,1]>y] <- y                   
  b <- diff(a[,1,drop=FALSE])
  b[b<=0] <- NA
  b <- c(1,b)
  a <- cbind(a,b)
  a <- na.omit(a)
  a <- a[,-c(3),drop=FALSE]
  return(a)}

vector <- function(X,Y,Z){                                            
  a <- rep(NA, X)
  a[Y] <- Z
  a[seq_len(min(Y)-1)] <- a[min(Y)]
  if(max(Y) < X){a[seq(max(Y)+1, X, 1)] <- 0}
  a <- approx(seq_along(a)[!is.na(a)],a[!is.na(a)],seq_along(a))$y
  b <- seq(1:X)
  c <- data.frame(X = b, Z = a)
  return(c)}

vector.final <- function(x,y){vector(x,matrix.validate(y,x)[,1],matrix.validate(y,x)[,2])}

ui <- 
  pageWithSidebar(
    headerPanel("Model"),
    sidebarPanel(
      sliderInput("periods","Nbr periods (X):",min=1,max=120,value=60),
      matrix2.input("vector_input",60,.2)
    ), # close sidebar panel
    mainPanel(plotOutput("graph1")) 
  ) # close page with sidebar
    
server <- function(input,output,session)({
 
  periods <- reactive(input$periods)
  vector_input <- reactive(input$vector_input)
  
  observeEvent(input$periods,{
    updateMatrixInput(session,"vector_input", 
                      value=matrix(c(input$periods,0.2),1,2, 
                                   dimnames=list(NULL, c("X","Y")))
    ) # close update matrix
  }) # close observe event
  
  output$graph1 <- renderPlot({plot({vector.final(periods(),vector_input())})})
   
}) # close server

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    在上面代码的Server部分中嵌入updateMatrixInput函数的updateMatrixInput函数中嵌入的matrix函数中(ok,从下数第7行代码),将值替换为0.2与input$vector_input[,2]。这为我清除了错误。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2021-11-26
      • 2021-11-22
      • 2017-12-14
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多