0

I would like the user to be able to select what variable they see on a popup in a leaflet map. It works when the variables are hard coded. However something is wrong with passing on a column header. Here is a reproducible example below, you'll notice when you select two variables that the map will appear but not with any data in the popups.

library(shiny)
library(sf)
library(leaflet)

ui <- fluidPage(
   titlePanel("test"),

      mainPanel(
         leafletOutput("map"),
         selectInput("var1", label = h5("Select Independent"), "", multiple = TRUE),
         selectInput("var2", label = h5("Select Dependent"), "", multiple = TRUE)             
      )
   )

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

  nc <- reactive({
    st_read(system.file("shape/nc.shp", package="sf"))
  })

  observe({
    updateSelectInput(
      session,
      "var1",
      choices=names(nc()))
  })

  observe({
    updateSelectInput(
      session,
      "var2",
      choices=names(nc()))      
  })

  output$map <- renderLeaflet({
    req(input$var1)
    req(input$var2)
    x <- as.character(input$var1)
    y <- as.character(input$var2)
    leaflet(nc()) %>% addTiles %>% addPolygons(
      popup = paste0("Var1: ", as.character(nc()$x),"<br>",
                    "Var2: ", as.character(nc()$y),"<br>")
    )
  })

}
shinyApp(ui = ui, server = server)
sbell423
  • 83
  • 10

1 Answers1

0

You need to use a double index instead of a dollar sign for passing a column name string, eg.

library(shiny)
library(sf)
library(leaflet)

ui <- fluidPage(
  titlePanel("test"),

  mainPanel(
    leafletOutput("map"),
    selectInput("var1", label = h5("Select Independent"), "", multiple = TRUE),
    selectInput("var2", label = h5("Select Dependent"), "", multiple = TRUE)             
  )
)

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

  nc <- reactive({
    st_read(system.file("shape/nc.shp", package="sf"))
  })

  observe({
    updateSelectInput(
      session,
      "var1",
      choices=names(nc()))
  })

  observe({
    updateSelectInput(
      session,
      "var2",
      choices=names(nc()))      
  })

  output$map <- renderLeaflet({
    req(input$var1)
    req(input$var2)
    x <- as.character(input$var1)
    y <- as.character(input$var2)
    leaflet(nc()) %>% addTiles %>% addPolygons(
      popup = paste0("Var1: ", as.character(nc()[[x]]),"<br>",
                     "Var2: ", as.character(nc()[[y]]),"<br>")
    )
  })

}
shinyApp(ui = ui, server = server) 
sebdalgarno
  • 2,351
  • 6
  • 23