I am developing an application shinyin which there is a map leaflet. The source dataset for the map includes latitude, longitude, and several other variables. I provide users with radio buttons, sliders, checkboxes, etc. that relate to these other variables with the effect of controlling which points are displayed on the map.
I include a basic example of my code below. Currently, I am pre-breaking my dataset into subsets, which can then be called in leafletvia a reactive expression (depending on what the user selects). This is a simple example with 4 subsets, so it may not seem right here. However, in my actual use case, the potential filter combinations that the user could select would be much larger.
Is it advisable to create ALL potential sub-discs that could be filtered in the Global.R script? Or should filtering be performed "on the fly" in reactive terms?
Also, is there an alternative to using a giant nested ifelse expression (e.g., relatively small, which I have below)? This is getting out of control as I add more user filtering options to my application. I don’t quite understand the order in which the reactive expression is updated when it can depend on several inputs.
The motivation for my question might be clearer if I shared a gigantic piece of code with all the filtering permutations, but first wanted to provide a simpler example:
library(shiny)
library(leaflet)
library(dplyr)
member <- 1:10
lat <- c(39.8, 39.6, 39.7, 39.78, 39.82, 39.74, 39.72, 38.9, 37.43, 38.0)
lon <- c(-86.1, -86.2, -86.3,-86.4,-86.5,-86.6,-86.7,-86.8,-86.9, -87)
group <- c("a","a","a","b","b","a","a","a","b","b")
year <- c(1,0,0,1,0,1,0,0,1,0)
data <- data.frame(member, lat, lon, group, year)
groupA_y1 <- data %>% filter(group == "a", year == 1)
groupA_y0 <- data %>% filter(group=="a", year == 0)
groupB_y1 <- data %>% filter(group=="b", year == 1)
groupB_y0<-data %>% filter(group=="b", year == 0)
ui <- fluidPage(
leafletOutput("mymap"),
radioButtons("group", "Group:", c("A", "B"), selected = "A"),
radioButtons("year", "Year", c(1,0), selected = 1)
)
server <- function(input, output, session) {
output$mymap <- renderLeaflet({
leaflet() %>%
addProviderTiles("CartoDB.Positron",
options = providerTileOptions(noWrap = TRUE)) %>%
setView(lng = -85.00, lat = 39.00, zoom = 6)
})
zerg <-reactive({
test<-ifelse(input$group=="A" & input$year==1, return(groupA_y1),
ifelse(input$group=="A" & input$year==0, return(groupA_y0),
ifelse(input$group=="B" & input$year==1, return(groupB_y1),
return(groupB_y0))))
return(test)
})
observe({
dataset<- zerg()
leafletProxy("mymap", data = dataset) %>%
clearMarkers() %>%
addCircleMarkers(~lon, ~lat, layerId=~member,
stroke=FALSE, fillOpacity=0.9, fillColor="Red")
})
}
shinyApp(ui, server)