Shiny Module that calls a reactive data set in parent Shiny server

后端 未结 2 2055
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 12:42

I\'m looking to port some older Shiny apps to use Shiny Modules, but running into trouble trying to port over my reactive expressions.

According to the documentation:

2条回答
  •  -上瘾入骨i
    2021-02-04 13:27

    If you want to pass input which is not part of the module just wrap it around reactive() as stated in a tutorial.

    If a module needs to access an input that isn’t part of the module, the containing app should pass the input value wrapped in a reactive expression (i.e. reactive(...)): callModule(myModule, "myModule1", reactive(input$checkbox1))

    Update: As correctly stated in another answer and Joe Cheng correct way to pass reactive expression is without brackets ()

    callModule(linkedScatter, "scatters", car_data)

    One option is also to modularize your API input function so you don't need to define reactive expression outside modules. Example of modularized input can be found from this answer. Below your code with right answer.

    library(shiny)
    library(ggplot2)
    
    linkedScatterUI <- function(id) {
      ns <- NS(id)
    
      fluidRow(
        column(6, plotOutput(ns("plot1"), brush = ns("brush"))),
        column(6, plotOutput(ns("plot2"), brush = ns("brush")))
      )
    }
    
    linkedScatter <- function(input, output, session, data, left, right) {
      # Yields the data frame with an additional column "selected_"
      # that indicates whether that observation is brushed
      dataWithSelection <- reactive({
        brushedPoints(data(), input$brush, allRows = TRUE)
      })
    
      output$plot1 <- renderPlot({
        scatterPlot(dataWithSelection(), left())
      })
    
      output$plot2 <- renderPlot({
        scatterPlot(dataWithSelection(), right())
      })
    
      return(dataWithSelection)
    }
    
    scatterPlot <- function(data, cols) {
      ggplot(data, aes_string(x = cols[1], y = cols[2])) +
        geom_point(aes(color = selected_)) +
        scale_color_manual(values = c("black", "#66D65C"), guide = FALSE)
    }
    
    ui <- fixedPage(
      h2("Module example"),
      linkedScatterUI("scatters"),
      textOutput("summary")
    )
    
    server <- function(input, output, session) {
    data(mpg)
      ### My modification 
      ### making the reactive outside of module call
      car_data <- reactive({
        mpg
        })
    
      ## Fix This doesn't work by reactive (var) no brackets()
      ## What is the syntax for being able to call car_data()?
      df <- callModule(linkedScatter, "scatters", reactive(car_data),
                       left = reactive(c("cty", "hwy")),
                       right = reactive(c("drv", "hwy"))
      )
    
      output$summary <- renderText({
        sprintf("%d observation(s) selected", nrow(dplyr::filter(df(), selected_)))
      })
    }
    
    shinyApp(ui, server)
    

提交回复
热议问题