我有一個閃亮的應用程式,它顯示一張地圖,可以根據 selectinput 功能選擇幾個國家。我正在嘗試用按鈕替換 selectInput,因此用戶應該能夠單擊按鈕,而不是選擇國家/地區,然后會出現下一個國家/地區。提前致謝
library(shiny)
library(leaflet)
df <- structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
"lat", "country", "number"), class = "data.frame", row.names = c(NA,
-4L))
ui <- (fluidPage(
titlePanel(title = "countries"),
sidebarLayout(
sidebarPanel( uiOutput("countrynames"),
shiny::actionButton("dd", "click")
),
mainPanel(leafletOutput("mymap", height = "500")
))
)
)
server <- function(input, output){
output$countrynames <- renderUI({
selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
c(as.character(df$country)))
})
map_data <- reactive({
data <- data.frame(df[df$country == input$country,])
data$popup <- paste0(data$country, " ", data$number)
return(data)
})
output$mymap <- renderLeaflet({
leaflet(data = map_data()) %>%
setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
addProviderTiles( provider = "CartoDB.Positron") %>%
addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
})
}
shinyApp(ui, server)
uj5u.com熱心網友回復:
您可以使用 areactiveVal來表示國家串列的索引來實作這一點。它將在按鈕單擊時更新。
library(shiny)
library(leaflet)
countries = c("China", "Russia", "USA", "Vietnam")
df <- structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
"lat", "country", "number"), class = "data.frame", row.names = c(NA,
-4L))
ui <- (fluidPage(
titlePanel(title = "countries"),
sidebarLayout(
sidebarPanel(
# uiOutput("countrynames"),
shiny::actionButton("dd", "click")
),
mainPanel(leafletOutput("mymap", height = "500")
))
)
)
server <- function(input, output){
output$countrynames <- renderUI({
selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
c(as.character(df$country)))
})
index = reactiveVal(1)
selected_country = reactive({
countries[index()]
})
observeEvent(input$dd,{
i = index() 1
if(i > length(countries)){
i = 1
}
index(i)
})
map_data <- reactive({
data <- data.frame(df[df$country == selected_country(),])
data$popup <- paste0(data$country, " ", data$number)
return(data)
})
output$mymap <- renderLeaflet({
leaflet(data = map_data()) %>%
setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
addProviderTiles( provider = "CartoDB.Positron") %>%
addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
})
}
shinyApp(ui, server)
要維護selectInput您可以使用updateSelectInput.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515261.html
標籤:r闪亮的传单
上一篇:根據部分匹配修剪串列
