将 R shiny 与 Leaflet 和 DataTable 与反应对象一起使用

Using R shiny with Leaflet and DataTable with reactive object

我对两天前在另一个 post (Getting Leaflet to work with Datatable selection in R shiny) 中提出的问题做了一个非常简化的版本 我离解决方案更近了。在 MA 的 4 个城市中有一个包含 12 个位置的 R 数据框。 dataTable 让用户 select 城市和传单地图将只显示所选城市中的位置。

library(shiny)
library(DT)
library(leaflet)
#Massmpg <- (read.csv("Massmpg.csv"))

City <- c("Boston","Boston", "Boston", "Lowell","Lowell", "Lowell","Worcestor", "Worcestor","Worcestor","Springfield","Springfield","Springfield")

lat <- c(42.35, 42.355, 42.345, 42.63,42.625,42.635,42.27,42.265,42.275, 42.1,42.105,42.095)

lng <- c(-71.05,-71.045,-71.055,-71.316,-71.315,-71.317,-71.79,-71.785,-71.795,-72.6,-72.595,-72.605)

MassLocations <- data.frame(City, lat,lng)


# MassLocations has 4 cities with 3 locations each
ui <- fluidPage(titlePanel("Mass mpg by location"),
                
                # Create a new Row in the UI for selectInputs
                fluidRow(
                    column(4,
                           selectInput("City",
                                       "City:",
                                       c("All",
                                         unique(as.character(MassLocations$City))))
                    ),
                            ),
                # Create a new row for the table.
                leafletOutput("map01"),
                DT::dataTableOutput("table")
                
)


server <- function(input, output) {
    
    dataShow <- reactive({
        DT::renderDataTable(DT::datatable({
            data <- MassLocations
            if (input$City != "All") {
                data <- data[data$City == input$City,]
                
            }
            data
        }))
    })
    

        # Filter data based on selections
        output$table <- dataShow()
        
        
        # map
        output$map01 <- renderLeaflet({
            #pal <- colorNumeric("YlOrRd", domain=c(min(quakes$mag), max(quakes$mag)))
            qMap <- leaflet(data = (dataShow())) %>% 
                addTiles() %>%
                addCircles(radius =3, color="red")
            qMap
        })
        
} 
        
# Run the application 
shinyApp(ui = ui, server = server)  '''

不幸的是,在闪亮的 window 首先打开然后崩溃后,我收到了一个错误。错误是 正在收听 http://127.0.0.1:7312 *警告:错误:没有活动的反应上下文不允许操作。

如果将 renderDataTable() 放在 reactive()

之外就可以正常工作
server <- function(input, output) {
  # Filter data based on selections
  dataShow <- reactive({
      data <- MassLocations
      if (input$City != "All") {
        data <- data[data$City == input$City, ]
      }
      data
    })

  # Display
  output$table <- DT::renderDataTable(
    DT::datatable(dataShow()))
...