【问题标题】:How do I show default values prior to triggering ObserveEvent in R shiny?如何在 R Shiny 中触发 ObserveEvent 之前显示默认值?
【发布时间】:2021-09-05 23:44:44
【问题描述】:

在运行下面的“简化工作代码”(RWC) 时,图 graph1 仅在用户点击可选的“显示矢量”按钮时出现。这是由 renderUI 函数触发的。

如何修改此设置,以便在首次调用应用程序时显示该图,然后再点击“SHOW VECTOR”?绘图值将反映 60 个周期(x 轴)和 0.20(y 轴)的默认值(就像在点击 SHOW VECTOR 按钮后立即出现绘图时一样,在用户使用第二个矩阵的输入修改绘图之前出现在侧边栏面板中)。

我觉得这是由于如何使用 renderUI 和 observeEvent。我不是这里的主人。

还有一个相关的问题——当应用程序重新运行时,所有值都应该返回到它们的默认值。但他们没有。运行应用程序,通过点击 SHOW VECTOR 按钮对变量 A 进行矢量化(在输入到左列之前从输入矩阵的右列开始 - 我已修复小矩阵错误)。出于测试目的检查全局变量,它们应该与您的输入相匹配(periods.R、vector_input.R、vector.R)。关闭应用程序,重新打开它,不要重置任何东西,现在就关闭它,这些全局变量应该已经恢复到它们的默认设置(A、B、C、D 都设置为 .20,从滑块输入设置为60)。但他们没有,只有 period.R 确实返回到默认设置 60。我几乎可以肯定这也是由于我对 renderUI/observeEvent 的错误使用造成的。

这里是 RWC(本可以进一步减少它,但保留骨架轮廓将有助于我将任何解决方案适应完整的工作应用程序;函数的机制可以忽略,因为它们工作正常):

library(shiny);library(shinyMatrix);library(shinyjs)

matrix1.input <- function(x) {
  matrixInput(
    x,
    value = matrix(c(0.2), 4, 1, dimnames = list(c("A","B","C","D"),NULL)),
    rows = list(extend = FALSE,  names = TRUE),
    cols = list(extend = FALSE, names = FALSE, editableNames = FALSE),
    class = "numeric")}

matrix2.input <- function(x,y,z){
  matrixInput(
    x,
    value = matrix(c(y,z),1,2,dimnames=list(NULL,c("Y","Z"))),
    rows = list(extend = TRUE,  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])}

### Shiny code ###
ui <- 
  pageWithSidebar(
    headerPanel("Model"),
    sidebarPanel(
      conditionalPanel(condition="input.tabselected==2",
               sliderInput('periods','',min=1,max=120,value=60),
               matrix1.input("base_input"),
               
               # Action buttons to conditionally show/hide performance vectors:
                 useShinyjs(),
                 actionButton('showPerfVectorBtn','Show vector'), 
                 actionButton('hidePerfVectorBtn','Hide vector'),
                 uiOutput("Vectors")),
    ), # close sidebar panel
    mainPanel(
      tabsetPanel(
          tabPanel("Dynamic", value=2,helpText("Dynamic model"),plotOutput("graph1")),
          id = "tabselected")
    ) # close main panel
  ) # close page with sidebar

server <- function(input,output,session)({
  # --- Set reactive input variables 
  periods       <- reactive(input$periods)
  base_input    <- reactive(input$base_input)
  vector_input  <- reactive(input$vector_input)
  
  # --- Link first row of vector input grids to base_input matrix
  observeEvent(input$periods|input$base_input,{
    updateMatrixInput(session,"vector_input", 
                      value=matrix(c(input$periods,input$base_input[1,1]),1,2, 
                                   dimnames=list(NULL, c("Y","Z")))
    ) # close update matrix
  }) # close observe event
  
  # --- Show performance vector if user elects
  output$Vectors <- renderUI({
    req(input$showPerfVectorBtn)
    tagList(matrix2.input("vector_input",input$periods,input$base_input[1,1]))
  }) # close render UI

  # Action buttons to conditionally show/hide performance vectors:
  observeEvent(input$showPerfVectorBtn, {shinyjs::show("Vectors")})
  observeEvent(input$hidePerfVectorBtn, {shinyjs::hide("Vectors")})

# Show plot:    
  output$graph1 <- renderPlot(plot(oe1(),type="b"))
  
# Capture inputs/outputs as global variables: periods.R, vector_input.R, vector_validate.R, vector.R
  observeEvent(periods(),{periods.R <<- periods()})
  observeEvent(base_input(),{base_input.R <<- base_input()})  
  observeEvent(vector_input(),{vector_input.R <<- vector_input()})
  observeEvent(matrix.validate(vector_input(),periods()), 
               {vector_validate.R <<- unique(matrix.validate(vector_input(),periods()))})
  oe1 <- reactive({req(periods(),vector_input())
    vector.final(periods(),vector_input())})
    observeEvent(oe1(),{vector.R <<- oe1()})    
}) # close server

# Create Shiny app ----
shinyApp(ui, server)

【问题讨论】:

  • 为了调试,我建议删除你的req 调用。这使得很难看到预期的反应链。
  • OK 将删除 req 调用,将简化代码并编辑问题。

标签: r shiny


【解决方案1】:

请看下面的解析代码。主要问题在于定义的功能;必须更改它们以反映应该在计算中使用的不同维度的输入矩阵。 renderPlot 也错误地调用了那些相同的定义函数。它现在在下面的最终代码中得到纠正。根据评论删除 req 让我走上了正确的道路,因为它的使用掩盖了定义函数的潜在问题。

library(shiny);library(shinyMatrix);library(shinyjs)

matrix1.input <- function(x){
  matrixInput(
    x,
    value = matrix(c(0.2), 4, 1, dimnames = list(c("A","B","C","D"),NULL)),
    rows = list(extend = FALSE,  names = TRUE),
    cols = list(extend = FALSE, names = FALSE, editableNames = FALSE),
    class = "numeric")}

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

matrix.validate <- function(x,y){
  a <- y  
  a[,1][a[,1]>x] <- x 
  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.base <- function(x,y){
  a <- rep(y,x)
  b <- seq(1:x)
  c <- data.frame(x = b, y = a)
  return(c)}

vector.multi <- 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.multiFinal <- function(x,y){vector.multi(x,matrix.validate(x,y)[,1],matrix.validate(x,y)[,2])}

ui <- 
  pageWithSidebar(
    headerPanel("Model"),
    sidebarPanel(
      conditionalPanel(condition="input.tabselected==2",
                       sliderInput('periods','',min=1,max=120,value=60),
                       matrix1.input("base_input"),
                       useShinyjs(),
                       actionButton('showBtn','Show vector'), 
                       actionButton('hideBtn','Hide vector'),
                       uiOutput("Vectors")),
    ), # close sidebar panel
    mainPanel(tabsetPanel(
        tabPanel("Dynamic", value=2,plotOutput("graph1")),
        id = "tabselected")
    ) # close main panel
  ) # close page with sidebar

server <- function(input,output,session)({
  periods       <- reactive(input$periods)
  base_input    <- reactive(input$base_input)
  vector_input  <- reactive(input$vector_input)

  observeEvent(input$periods|input$base_input,{
    updateMatrixInput(session,"vector_input", 
                      value=matrix(c(input$periods,input$base_input[1,1]),1,2, 
                                   dimnames=list(NULL, c("Y","Z")))
    ) # close update matrix
  }) # close observe event
  
  # --- Show performance vector if user elects
  output$Vectors <- renderUI({
    req(input$showBtn)
    tagList(matrix2.input("vector_input",input$periods,input$base_input[1,1]))
  }) # close render UI
  
  observeEvent(input$showBtn, {shinyjs::show("Vectors")})
  observeEvent(input$hideBtn, {shinyjs::hide("Vectors")})
  
  output$graph1 <- renderPlot(
    if(input$showBtn == 0)
      plot(vector.base(periods(),input$base_input[1,1]),type="b")
    else
      plot(vector.multiFinal(periods(),matrix.validate(periods(),vector_input())),type="b")
    ) # close render plot
 }) # close server

shinyApp(ui, server)

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2019-08-01
    • 2018-03-12
    • 2021-09-07
    • 2017-11-06
    • 2016-04-19
    • 2021-12-21
    • 2022-01-19
    • 2020-07-02
    相关资源
    最近更新 更多