所以我在SO上发现了一个非常相似的问题,但我无法解决我的问题。我正在用 Shiny 传单制作地图。我想要的是,当某个变量具有某些值(条件)时,制作一个addAwesomeMarkers()
; 否则,制作一个addCircleMarkers()
. 我已经尝试了一些if (else)
,case_when()
和mutate()
声明,但无法修复它。所以......这是我的代码。
套餐:
library(dplyr)
library(ggplot2)
library(leaflet)
library(reshape2)
library(shiny)
library(tidyr)
虚拟数据集:
NAME VAR WAIT latitude longitude
a 4 1 52,6263 4,7312
b 3 52,2946 4,9585
c 6 8 52,3331 6,6468
d 8 5 51,2864 4,0492
e 7 6 50,9832 5,8446
代码:
leafletOutput('myMap', width = '80%', height = 600)
output$myMap <- renderLeaflet({
getColor <- function(DATASET) {
sapply(DATASET$WAIT, function(WAIT) {
if(WAIT == 0 | is.na(WAIT) | is.nan(WAIT)) {"gray"}
else if(WAIT <= 1){"darkgreen"}
else if(WAIT <= 2){"green"}
else if(WAIT <= 4){"lightgreen"}
else if(WAIT <= 6){"orange"}
else if(WAIT <= 8){"red"}
else {"darkred"}
})
}
icons <- awesomeIcons(
icon = 'heart-o',
lib = 'fa',
iconColor = "#FFFFFF",
markerColor = getColor(DATASET))
map <- leaflet(DATASET) %>%
addTiles() %>%
# DATASET$VAR is a char in my dataset
{if (DATASET$VAR == "4") filter(., addAwesomeMarkers(lng = ~longitude, lat = ~latitude, icon = icons,
label = ~as.character(DATASET$NAME),
popup = paste0("<strong>Name: </strong>", DATASET$NAME)))
else filter(., addCircleMarkers(lng = ~longitude, lat = ~latitude, radius = 10, label = ~as.character(DATASET$NAME),
popup = paste0("<strong>Name: </strong>", DATASET$NAME)))} %>%
addProviderTiles(providers$OpenStreetMap)
})
所以我的 if else 不起作用;给出以下错误:
no applicable method for 'filter_' applied to an object of class "c('leaflet', 'htmlwidget')"
我尝试实现一个mutate()
. 提前感谢您的帮助!