我的目标是创建一个基于下拉菜单突出显示状态的地图。我已经制作了一个适用于数据集中某个指标的地图,但是当我尝试在闪亮的应用程序中重新创建地图时,状态都是灰色而不是变化的绿色阴影。这是我的代码:
library(shiny)
library(tidyverse)
library(leaflet)
library(dplyr)
library(tigris)
library(DT)
library(rgdal)
library(RColorBrewer)
#create the UI
ui <- fluidPage(
#create title
titlePanel("Interactions by State"),
sidebarLayout(
sidebarPanel(
selectInput("interactionMetric",
label = "Choose a Metric",
choices = c("Sentiment",
"Average Totals",
"Management Fee"),
selected = "Sentiment")
),
mainPanel(
leafletOutput("mymap"),
p()
)
)
)
#Create the server
server <- function(input, output, session) {
#get the data
primaryDf <- read.csv('InteractionsFormattedFirstMonth.csv', header = TRUE, sep = ',')
#select the input
decision <- reactive({
switch(input$interactionMetric,
"Sentiment" = primaryDf$Average.of.Average.Sentiment,
"Average Totals" = primaryDf$Average.of.Event.Value,
"Management Fee" = primaryDf$Average.of.MGT.Fee)
})
#create dataframe based on input
newDf <- reactive({
cbind(primaryDf["Row.Labels"],decision())
})
#create the states and join with dataframe to create spatial object
statesUsed <- states(cb=T)
states_merged <- reactive({
geo_join(statesUsed, newDf(), "STUSPS", "Row.Labels", how = 'inner')
})
#create the function for a color pallette
pal <- reactive({
colorQuantile("YlGn", states_merged()$decision, n = 5)
})
#create the map to be rendered in the UI
output$mymap <- renderLeaflet({
leaflet(data = states_merged()) %>%
addProviderTiles("CartoDB.Positron") %>%
setView(-98.483330, 38.712046, zoom = 4) %>%
addPolygons(data = states_merged(),
fillColor = ~pal(),
fillOpacity = 0.7,
weight = 0.2,
smoothFactor = 0.2
)
})
}
shinyApp(ui, server)
供参考,这里有数据:
> head(primaryDf)
UniqueID Row.Labels Average.of.Event.Value Average.of.Average.Sentiment Average.of.MGT.Fee Sum.of.UniqueID
1 1 AL 4.000000 3.000000 600.0000 311
2 2 AR 1.500000 3.000000 600.0000 83
3 3 AZ 3.600000 3.000000 560.0000 736
4 5 CA 4.567568 3.138108 883.7838 4346
5 6 CO 3.000000 3.167500 450.0000 389
6 7 CT 6.333333 3.033333 500.0000 249
此时的代码会生成美国地图,数据集中包含的所有状态都将显示为灰色。作为修复,我尝试了这个:
addPolygons(data = states_merged(),
fillColor = ~pal(states_merged()$decision),
fillOpacity = 0.7,
weight = 0.2,
smoothFactor = 0.2
)
但是,这会导致错误&#34;未使用的参数(states_merged()$ decision)&#34; 感谢任何人可以帮我解决这个问题,我已经连续几天不停地挣扎,这让我发疯了!
答案 0 :(得分:0)
我找到了这个参考:https://github.com/rstudio/shiny/issues/858
解决方案是pal()是一个函数,但由于某种原因,要传递给它的数据必须紧挨着它。这真的很奇怪,但这是工作代码的样子:
output$mymap <- renderLeaflet({
leaflet(data = states_merged()) %>%
addProviderTiles("CartoDB.Positron") %>%
setView(-98.483330, 38.712046, zoom = 4) %>%
addPolygons(data = states_merged(),
#note the solution here, "pal()(decision())
fillColor = ~pal()(decision()),
fillOpacity = 0.7,
weight = 0.2,
smoothFactor = 0.2
)
})
}