0

我希望用户能够选择他们在传单地图的弹出窗口中看到的变量。它在变量被硬编码时起作用。但是,传递列标题有问题。下面是一个可重现的示例,您会注意到,当您选择两个变量时,地图将出现,但弹出窗口中没有任何数据。

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)
4

1 回答 1

0

您需要使用双索引而不是美元符号来传递列名字符串,例如。

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) 
于 2018-02-27T05:38:57.933 回答