我正在构建我的第一个闪亮的交互式应用程序,来自https://www.kaggle.com/c/bike-sharing-demand的自行车共享数据。用户可以用单选按钮选择“起点站点”或“终点站点”,然后在地图上接收圆形标记,半径是某个自行车站点在特定日期旅行的开始/结束计数。
我有一个包含trip数据的数据帧(df.trip)和一个包含每个站点的坐标(df.station)的数据帧。根据用户的选择,我将不得不使用'from_station_id‘或'to_station_id’向左连接df.station,以便找到起点/终点站的坐标。
我已经在UI中实现了单选按钮,并且已经有了日期功能。但是,我尝试了许多方法来获得一个响应式的if语句,该语句根据用户的选择在不同的键上连接数据帧。在if中,还有其他的反应式语句。下面提供的是服务器的一部分。
我收到了Error in .getReactiveEnvironment()$currentContext() : Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
station_type <- reactive({
if (toString(input$station)=="Start Station") {
return(TRUE)
} else {
return(FALSE)
}
})
if (station_type() == TRUE) {
filtered <- reactive({
df.trip %>%
filter(format(df.trip$starttime,"%Y-%m-%d") == input$date) %>%
group_by(from_station_id) %>%
summarize(n_trips = n())
)}
tmp.df <- reactive({
left_join(filtered(), df.station, by = c("from_station_id" = "station_id"))
})
leaflet(tmp.df()) %>%
addTiles(group="OSM") %>%#OSM is default tile providor
addProviderTiles(providers$CartoDB.Positron) %>%
setView(
lng=-122.335167,
lat=47.608013,
zoom=12
)%>%
addCircleMarkers(lng = ~long, lat = ~lat, weight = 1,label=~name,
radius = ~n_trips)
}
else {
filtered <- reactive({
df.trip %>%
filter(format(df.trip$starttime,"%Y-%m-%d") == input$date) %>%
group_by(to_station_id) %>%
summarize(n_trips = n())
)}
tmp.df <- reactive({
left_join(filtered(), df.station, by = c("to_station_id" = "station_id"))
})
leaflet(tmp.df()) %>%
addTiles(group="OSM") %>%#OSM is default tile providor
addProviderTiles(providers$CartoDB.Positron) %>%
setView(
lng=-122.335167,
lat=47.608013,
zoom=12
)%>%
addCircleMarkers(lng = ~long, lat = ~lat, weight = 1,label=~name,
radius = ~n_trips)
}
})````发布于 2019-01-11 18:58:44
该错误是由于您试图在renderLeaflet函数外部呈现小叶贴图造成的。您还可以将if部分减少到仅相关部分,并将其全部包含在您的renderLeaflet调用中。
因此,如果您已经在使用leafletOutput(outputId = "map")的UI中设置了leaflet地图,那么在服务器中应该可以这样做:
output$map <- renderLeaflet({
from_to <- input$station
df <- df.trip %>%
filter(format(df.trip$starttime,"%Y-%m-%d") == input$date)
if (from_to == "Start Station") {
df <- df %>%
group_by(from_station_id) %>%
summarize(n_trips = n()) %>%
left_join(df.station, by = c("from_station_id" = "station_id"))
} else {
df <- df %>%
group_by(to_station_id) %>%
summarize(n_trips = n()) %>%
left_join(df.station, by = c("to_station_id" = "station_id"))
}
leaflet(df) %>%
addTiles(group="OSM") %>%#OSM is default tile providor
addProviderTiles(providers$CartoDB.Positron) %>%
setView(
lng=-122.335167,
lat=47.608013,
zoom=12
)%>%
addCircleMarkers(lng = ~long, lat = ~lat, weight = 1,
label=~name, radius = ~n_trips)
})https://stackoverflow.com/questions/54144313
复制相似问题