我有一个数据框如下
d <- data.frame(number = 1:4,
date = c(1600, 1700, 1800, 1900),
T_name = c("name1", "name2", "name3", "name4"))
我一直在尝试让我的地图对选择输入做出反应,但它不起作用。下面的代码使用适当的下拉列表加载应用程序,地图出现,但是当我从列表中选择某些内容时,传单地图没有反应。
有人能看出我哪里可能出错吗?
用户界面代码
library(shiny)
library(leaflet)
ui <- fluidPage("name_of_map",
sidebarLayout(
sidebarPanel(
selectInput(inputId = "input1", label = "Name of Filter" ,choices =
unique(d$T_name)),
selectizeInput(inputId = "year", label = "Year of Event",
choices = unique(d$date))
),
mainPanel(
leafletOutput("mymap"))
)
)
服务器代码
server <- function(input, output) {
output$mymap <- renderLeaflet({
leaflet(data = d[1:25,]) %>% addTiles() %>%
addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
addMarkers(lng=~longitude, lat=~latitude,
popup = ~paste(mname, "<br>", "Date:", date,
"<br>", "Number of casualties:",
casualties,"<a href=",d$web,">",d$web, main=input$input1)
)
})
}
reactive <- reactive({d})
shinyApp(ui, server)
您的示例中缺少一些输入变量,尤其是坐标(长/纬度)、mname、web、casualities。通过您的构建,应用程序永远不会改变,因为无功值始终选择数据框 d,但它永远不会按名称或年份过滤数据。所以你必须稍微调整一下你的反应函数。在这里我按名称或年份进行过滤。其中任一条件必须为真。
我稍微改变了你的代码,所以至少其他人可以重现它,并且我将你的反应移到了服务器功能中。
d <- data.frame(number = 1:4,
date = c(1600, 1700, 1800, 1900),
longitude = runif(4, 13,18),
latitude = runif(4, 40, 55),
web= rep("www.whatever.com", 4),
T_name = c("name1", "name2", "name3", "name4"))
library(shiny)
library(leaflet)
ui <- {fluidPage("name_of_map",
sidebarLayout(
sidebarPanel(
selectInput(inputId = "input1", label = "Name of Filter" ,choices =
unique(d$T_name)),
selectizeInput(inputId = "year", label = "Year of Event",
choices = unique(d$date))
),
mainPanel(
leafletOutput("mymap"))
)
)}
server <- function(input, output) {
react <- reactive({
req(input$input1)
req(input$year)
df <- d[d$T_name == input$input1 | d$date == input$year,]
df
})
output$mymap <- renderLeaflet({
req(input$input1)
leaflet() %>% addTiles() %>%
addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
addMarkers(lng=react()$longitude, lat=react()$latitude,
popup = paste("mname", "<br>", "Date:", react()$date,
"<br>", "Number of casualties:",
"casualties", "<a href=", react()$web, ">", main=input$input1)
)
})
}
shinyApp(ui, server)