我认为对这些ID进行分组仍然是不错的选择。这个分组变量可以被添加到你的数据框中,你可以使用它来切换显示/隐藏点,如下图所示。这与你最初的尝试没有什么不同,因为你仍然必须明确指出你想删除哪些ID。你仍然必须这样做,但是现在你必须将它们放在确定的组中。
require(shiny)
require(leaflet)
require(dplyr)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
#Set value = TRUE so points are shown by default
checkboxInput("delete1", "Toggle ID 1 and 2", value = TRUE),
checkboxInput("delete3", "Toggle ID 3", value = TRUE)
),
mainPanel(
leafletOutput("map")
)
)
))
df <- data.frame(
id = c(1,2,3),
#Add grouping variable
group = c("one", "one", "two"),
lng = rnorm(3, -106.1039361, 0.5) ,
lat = rnorm(3, 50.543981, 0.5)
)
server <- shinyServer(function(input, output, session) {
output$map <- renderLeaflet(
leaflet() %>%
addTiles() %>%
#Add markers with group
addCircleMarkers(group = df$group, df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
)
observeEvent(input$delete1, {
proxy <- leafletProxy('map')
#Always clear the group first on the observed event
proxy %>% clearGroup(group = "one")
#If checked
if (input$delete1){
#Filter for the specific group
df <- filter(df, group == "one")
#Add the specific group's markers
proxy %>% addCircleMarkers(group = df$group, df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
}
})
#Repeat for the other groups
observeEvent(input$delete3, {
proxy <- leafletProxy('map')
proxy %>% clearGroup(group = "two")
if (input$delete3){
df <- filter(df, group == "two")
proxy %>% addCircleMarkers(group = df$group, df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
}
})
})
shinyApp(ui, server)
,你可以使用另一个想法是不是一个checkboxInput
的是selectInput
,你可以在一个选择的倍数。这将为每组保存observeEvents
。如下所示。我设置它,所以它默认显示所有的点,如果你选择一个组,它将从图中删除。
require(shiny)
require(leaflet)
require(dplyr)
df <- data.frame(
id = c(1,2,3),
#Add grouping variable
group = c("one", "one", "two"),
lng = rnorm(3, -106.1039361, 0.5) ,
lat = rnorm(3, 50.543981, 0.5)
)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
#Set value = TRUE so points are shown by default
selectInput("toggle", "Toggle Groups", choices = unique(df$group), multiple = TRUE)
),
mainPanel(
leafletOutput("map")
)
)
))
server <- shinyServer(function(input, output, session) {
output$map <- renderLeaflet(
leaflet() %>%
addTiles() %>%
addCircleMarkers(df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
)
observe({
proxy <- leafletProxy('map')
if(is.null(input$toggle)){
proxy %>% clearMarkers() %>%
addCircleMarkers(df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
} else {
#Always clear the shapes on the observed event
proxy %>% clearMarkers()
#Filter for the specific group
df <- filter(df, !(group %in% input$toggle))
#Add the specific group's markers
proxy %>% addCircleMarkers(group = df$group, df$lng, df$lat, radius=2, fill = TRUE, color = 'red')
}
})
})
shinyApp(ui, server)
的例子是3个id和证明有时我必须添加/删除分组数据。真正的问题有大约一百万个ID,所以我希望避免把它们分成几组。 – DS501
在你的例子中,即使你不叫它们,你也会把它们分组。 'removeMarker(df [1:2,1])'将ID 1和ID 2组合在一起。如果通过数据框中的某个变量将它们分组在一起,那么可以使用我在其他答案中显示的selectInput概念避免大量重复代码(必须为每个组使用新的'observeEvent')。 – Jake