我認爲對這些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