Blaiso
Blaiso

Reputation: 309

How can I get Leaflet to ignore NULL or empty objects

In the actual problem this variable is created by a script filtering the coordinates specified by the user, so sometimes variables return NULL. After specifying the coordinates I want to run the rest of the script without editing any part of it.

For simplicity I have used the breweries dataset to represent this.

##load required package    

    library(mapview)
    library(leaflet)

##create variable with points

    breweries_A <- breweries

##create variable with no points    

    breweries_B <- NULL

##create a leaflet plot

    breweries_plot <- leaflet() %>% 
      addProviderTiles('CartoDB.Positron') %>%
      addCircleMarkers(data = breweries_A) %>%
      addCircleMarkers(data = breweries_B)

The result is an error because breweries B has no data.

Therefore it would be really helpful if there was a way to make leaflet ignore NULL objects, or dataframes with no rows?

Upvotes: 0

Views: 587

Answers (1)

Kent Johnson
Kent Johnson

Reputation: 3388

You can add the data conditionally to the map:

breweries_plot <- leaflet() %>% 
  addProviderTiles('CartoDB.Positron') 

if (!is.null(breweries_A))
  breweries_plot <- breweries_plot %>% addCircleMarkers(data = breweries_A)
if (!is.null(breweries_B))
  breweries_plot <- breweries_plot %>% addCircleMarkers(data = breweries_B)

Upvotes: 2

Related Questions