首页 > 解决方案 > 在 R/Shiny 中,如何使用操作按钮触发观察事件?

问题描述

这是我上一篇文章“在R/Shiny中,如何使用Action Button触发观察事件功能?”的简化版本。

下面的代码在 Reactive 的基础上输出用户输入图,因此用户可以查看他的输入构建。情节需要保持反应性(不链接到动作按钮的点击)。下面代码中的观察事件从这些输入中创建了一个 R 对象(称为“matrix_inputs.R”),用于此处未显示的另一个 R 函数。我想让用户在用户单击操作按钮时将该输入数据保存到 R 对象中(触发观察事件)。然后,用户可以继续将更多数据输入到输入矩阵中,并在不改变 R 对象的情况下,在反应的基础上观察绘图变化。如果用户在进行这些进一步更改后再次单击操作按钮,则更新的数据将被保存并覆盖在 Observe Event 中创建的同一个 R 对象。

我知道我应该在观察事件中插入“input$go, {...}”。它不在下面的代码中,因为如果我插入它,应用程序将无法工作,它会立即崩溃。我尝试了各种迭代,但都没有运气。有人对如何使这项工作有任何见解吗?保持情节完全实时反应,同时将观察事件链接到操作按钮。

这是代码:

library(shiny)
library(shinyMatrix)

m <- matrix(c(1,1), 1, 2, dimnames = list(NULL, c("Y", "Z"))) 

ui <- fluidPage(   
  
  titlePanel("Vector Generator"),   
  
  sidebarPanel(
    width = 6,     
    tags$h5(strong("Matrix inputs:")),     
    matrixInput("matrix_input",
                value = m,
                rows = list(extend = TRUE, names = TRUE, editableNames = TRUE),
                cols = list(extend = FALSE, names = TRUE, editableNames = FALSE),
                class = "numeric")
  ), # closes sidebarPanel
  
  actionButton(inputId = "go",label = "Save data"),
  
  mainPanel(
    
    h5(strong("Plot of matrix inputs:")),
    width = 6,plotOutput("graph"),
    
    h5(strong("Table of matrix inputs:")),
    tableOutput("view"),
  
  ) # closes main panel
)   # closes user input (UI) section

server <- function(input, output, session) {   
  
  matrix_input <- reactive(input$matrix_input)

  # Captures input data for further processing in R ----
  observeEvent(matrix_input(), {matrix_input.R <<- unique(matrix_input())})
  
  output$graph <- renderPlot({     
    plot(matrix_input(),type="b")
  }) 
  
  output$view <- renderTable({
    matrix_input()
  })
  
} # closes user server section

shinyApp(ui, server)

标签: rshinyshiny-reactivity

解决方案


假设我对你的理解是正确的,并且你想在用户按下“Go”时渲染绘图,我会为你的服务器尝试这个:


server <- function(input, output, session) {   
  
  matrix_input <- reactive(input$matrix_input)

  # Captures input data for further processing in R ----
  
  observeEvent(input$go, {
   matrix_input.R <<- unique(matrix_input)
  }

  output$graph <- renderPlot({     
    plot(matrix_input(),type="b")
  }) 
  
  output$view <- renderTable({
    matrix_input()
  })
} # closes user server section

当用户按下“go”而不是之前,这应该运行图


推荐阅读