我正在尝试使用数据中的过滤器打印到交互式地图,但是我收到一条错误消息,提示未提供经度和纬度点。
我提供了我的代码的副本和数据示例。
library(shiny)
library(leaflet)
library(dplyr)
library(stringr)
library(ggplot2)
#import data
data <- structure(list(VictimSex = structure(c(2L, 2L, 4L, 4L, 2L), .Label = c("",
"F", "H", "M", "N", "X"), class = "factor"), Long = c("34.0508",
"33.8542", "34.1052", "34.0255", "33.9997"), Lat = c("-118.2731",
"-118.2905", "-118.3252", "-118.3548", "-118.2827")), row.names = c(NA,
5L), class = "data.frame")
#Define UI ----
ui <- fluidPage(
titlePanel("Interactive Los Angeles Traffic COllision"),
sidebarLayout(
sidebarPanel(
checkboxGroupInput("Gender", h3("Gender"), choices = list("F", "M"), selected = "Female")
),
mainPanel(leafletOutput("map", "100%", 500),
plotOutput("bar"))
)
)
#Define Server logic ----
server <- function(input, output, session) {
filtered <- reactive ({
if (is.null(input$Gender)){
return(NULL)
}
data %>% filter(VictimSex %in% input$Gender)
})
output$map <- renderLeaflet({
leaflet()%>%
addProviderTiles("CartoDB") %>%
addCircleMarkers(data = filtered(), radius = 2)
})
}
#Run the app ----
shinyApp(ui, server)
我收到的错误是:找不到点数据;请为addCircleMarkers提供数据和/或lng / lat参数
您的代码中有3个问题。
1-当未设置input $ Gender时,filtered
反应式返回NULL。
修复:在函数的开头添加req
a,以便在设置输入之前不会触发它。
req(input$Gender)
一种替代方法是,如果没有过滤器处于活动状态,则返回完整的数据集。只需将return(NULL)
替换为return(data)
2-纬度/经度数据为文本,而应为数字。
修复:您可以通过在代码开头使用as.numeric()
进行转换
data$Lat <- as.numeric(data$Lat)
data$Long <- as.numeric(data$Long)
3-纬度和经度倒置。
修复:您可以交换列值
tmpLat <- data$Long
data$Long <- data$Lat
data$Lat <- tmpLat