首页 > 解决方案 > shiny - 使用 eventReactive 根据输入更新数据

问题描述

相当新,试图在更新数据时shiny进行整理。eventReactive就我而言,我希望data.frame dat.base不重新计算 ,除非更新输入 ( textInput a2)。与stoch_data对象相反,在更新两个输入中的任何一个时都应重新计算该对象。我似乎无法弄清楚如何dat.base创建(我object 'dat.base' not found每次包装时dat.base都会收到错误eventReactive.

我究竟做错了什么?感谢您的任何指导...

最小的例子:

library(plyr)
library(dplyr)
library(tidyr)
library(ggplot2)

library(shiny)
library(shinydashboard)
    
sidebar <- dashboardSidebar(
    textInput(inputId = "a1", label = "First", 
                value = "10"),
                                        
    textInput(inputId = "a2", label = "Second", 
                value = "20")
)


server <- function(input, output) {
    stoch_data <- reactive({
        a1 <- as.numeric(input$a1)
        a2 <- as.numeric(input$a2)
        stoch_output <- data.frame(a1 = a1, a2 = a2)        
        }) 

    output$plot2 <- renderPlot({
        a1 <- 10
        a2 <- as.numeric(input$a2)
        
        eventReactive(input$a2, {
        dat.base <- data.frame(a1, a2) %>% 
                                                mutate(Source = "Baseline input parameters")
                                        }, ignoreNULL=FALSE)

        dat <- stoch_data() %>%
                mutate(Source = "User-provided input parameters") %>%
                rbind(dat.base) 
                
        ggplot(dat) +
            geom_point(aes(x = a1, y = a2)) +
            facet_wrap(~ Source)
        }) 
} 

body <- dashboardBody(
    mainPanel(plotOutput("plot2"), width = 350 ))

ui <- dashboardPage(sidebar = sidebar,
    body = body,
    header = dashboardHeader()
        )
                    
shinyApp(ui, server)

标签: rshinyreactive

解决方案


你应该把eventReactive()外面的output$plot2. 尝试这个

server <- function(input, output) {
  stoch_data <- reactive({
    a1 <- as.numeric(input$a1)
    a2 <- as.numeric(input$a2)
    stoch_output <- data.frame(a1 = a1, a2 = a2)        
  }) 
  
  dat.base <- eventReactive(input$a2, {
    a1 <- 10
    a2 <- as.numeric(input$a2)
    dat.base <- data.frame(a1, a2) %>% 
      mutate(Source = "Baseline input parameters")
  }, ignoreNULL=FALSE)
  
  output$plot2 <- renderPlot({
    
    dat <- stoch_data() %>%
      mutate(Source = "User-provided input parameters") %>%
      rbind(dat.base()) 
    
    ggplot(dat) +
      geom_point(aes(x = a1, y = a2)) +
      facet_wrap(~ Source)
  }) 
} 

推荐阅读