jpinelo jpinelo - 3 months ago 41
R Question

Reactive mapping after checkboxGroupInput

I'm new to shiny and leaflet and I would appreciate any pointers. The code below is an attempt to map points over a base map. It works, but not reactively.

The points come from a data frame (imported from CSV), which I can map. However, at the top of the app, I created a checkbox to let the user choose features. The idea is that selection will determine which rows are passed forwards, and therefore which points are mapped. This is the step I'm struggling with. In the code, I'm now passing the full list of possible points from the data frame, not from the output of the filtering (checkbox input). How do I pass the result of the filtering process instead?

My approach is to grab the cols with coordinates to create a data frame with

cbind()
, passing this to
points
; but perhaps one could pass the relevant cols from the filtered data directly. Thank you.

library(shiny)
library(leaflet)
library(dplyr)


parks <- read.csv("data.csv")

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
# First row for selectInputs
fluidRow(
column(4,
checkboxGroupInput(inputId = "d_Governorate",
label = "Governorate:",
choices = c("All",
unique(as.character(parks$Governorate))),
selected = "All"
)
),

leafletOutput("d_map")
)
)



server <- function(input, output, session) {

points <- reactive({
validate(
need(input$d_Governorate != "", 'Please choose at least one feature.')
)
temp <- select(parks, lon, lat)
if (input$d_Governorate != "All") {
temp <- filter(parks, Governorate %in% input$d_Governorate) %>%
select(lon, lat)
}
temp
}),

output$d_map <- renderLeaflet({
leaflet() %>%
addProviderTiles("Stamen.TonerLite",
options = providerTileOptions(noWrap = TRUE)
) %>%
addMarkers(data = points())
})
}

shinyApp(ui, server)


DATA:
https://www.dropbox.com/s/3nq07fbyurur8ec/data.csv?dl=0

Answer

I would change the part where you define the point reactive variable with the following code (the code uses the dplyr package):

        points <- reactive({
            validate(
                    need(input$d_Governorate != "", 'Please choose at least one feature.')
            )
            temp <- select(parks, lon, lat)
            if (input$d_Governorate != "All") {
                    temp <- filter(parks, Governorate %in% input$d_Governorate) %>% 
                            select(lon, lat)
            }
            temp
    })

In the UI part add the:

selected = "All"

to the checkboxGroupInput definition.