Skip to content

Instantly share code, notes, and snippets.

@dholstius
Created April 16, 2015 16:07
Show Gist options
  • Save dholstius/b02491c8ace4be327d7c to your computer and use it in GitHub Desktop.
Save dholstius/b02491c8ace4be327d7c to your computer and use it in GitHub Desktop.
Reactive context for leaflet() in dynamic Rmarkdown document (runtime:shiny)
---
title: "Reactive Leaflet"
author: "David Holstius"
date: "April 16, 2015"
output: html_document
runtime: shiny
---
## Problem Description
**How should one provide a reactive context to `leaflet()`?**
This naïve attempt fails with:
> Quitting from lines 14-37 (Untitled.Rmd)
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.)
... if the line beginning with `subset` is uncommented.
```{r, echo=FALSE}
set.seed(123)
rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
rand_z = function(n = 10) rnorm(n, mean = 0, sd = 1)
library(sp)
my_spdf <- SpatialPointsDataFrame(
coords = cbind(rand_lng(50), rand_lat(50)),
data = data.frame(z = rand_z(50)))
library(shiny)
selectizeInput(
inputId = "threshold",
label = "Threshold",
choices = c("Zero" = 0.0, "One" = 1.0),
selected = 0.0)
library(leaflet)
my_spdf %>%
# subset(z > input$threshold) %>%
leaflet() %>%
addTiles() %>%
addCircles()
```
@ramnathv
Copy link

So, basically do

renderLeaflet(
  my_spdf %>%
    ...
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment