根据您的需要,您可以使用两个选项之一。
1) 将值存储到reactiveValues()中。在这种情况下,国家名单将在该届会议期间保持不变。
2) 要将该值存储在全局值中,它将在会话之间持久化,并可在会话/用户之间访问(您可以将赋值放在global.R中)。
编辑:在选项2中,添加了检测新国家的代码。
注意:在下面的示例中,我添加了一个控件来监视国家列表。
选项1示例
library(shiny)
library(DT)
library(leaflet)
library(rgdal)
library(maptools)
library(rgeos)
ui <- fluidPage(leafletOutput("mymap") ,
verbatimTextOutput('myCountries'))
countries <- readShapeSpatial("TM_WORLD_BORDERS_SIMPL-0.3.shp")
displayed <- c("United Kingdom")
server <- function(input, output, session) {
r <- reactiveValues()
observe({
r$displayed <- unique(c(r$displayed, pointsInBounds()))
})
output$mymap <- renderLeaflet({
leaflet(countries) %>%
addTiles() %>%
setView(lng = -0.1294984,
lat = 51.4992921,
zoom = 10)
})
output$myCountries <- renderPrint({
r$displayed
})
pointsInBounds <- reactive({
if (is.null(input$mymap_bounds)) {
return(NULL)
}
bounds <- input$mymap_bounds
N <- bounds$north
S <- bounds$south
E <- bounds$east
W <- bounds$west
BB = matrix(c(W, E, E, W, W, N, N, S, S, N), nrow = 5, ncol = 2)
BB = SpatialPolygons(list(Polygons(list(Polygon(
BB
)), 1)))
as.vector(countries[which(gIntersects(countries, BB, byid = TRUE)),]$NAME)
})
}
shinyApp(ui, server)
选项2示例
library(shiny)
library(DT)
library(leaflet)
library(rgdal)
library(maptools)
library(rgeos)
ui <- fluidPage(leafletOutput("mymap") ,
verbatimTextOutput('myCountries'))
countries <- readShapeSpatial("TM_WORLD_BORDERS_SIMPL-0.3.shp")
if (!exists('displayed')){
displayed <<- c("United Kingdom")
}
server <- function(input, output, session) {
observe({
current.coutries <- pointsInBounds()
new.countries <- current.coutries[ ! (current.coutries %in% displayed) ]
# DOWNLOAD new.countries
displayed <<- unique(c(displayed, pointsInBounds()))
})
output$mymap <- renderLeaflet({
leaflet(countries) %>%
addTiles() %>%
setView(lng = -0.1294984,
lat = 51.4992921,
zoom = 10)
})
output$myCountries <- renderPrint({
pointsInBounds()
displayed
})
observeEvent(input$mymap_bounds, {})
pointsInBounds <- reactive({
if (is.null(input$mymap_bounds)) {
return(NULL)
}
bounds <- input$mymap_bounds
N <- bounds$north
S <- bounds$south
E <- bounds$east
W <- bounds$west
BB = matrix(c(W, E, E, W, W, N, N, S, S, N), nrow = 5, ncol = 2)
BB = SpatialPolygons(list(Polygons(list(Polygon(
BB
)), 1)))
as.vector(countries[which(gIntersects(countries, BB, byid = TRUE)),]$NAME)
})
}
shinyApp(ui, server)