2

In R (shiny) I'm using Leaflet. I want to use a geojson file with polygons; each polygon has an id. I also want to use a csv-file with measurements for every id in the geojson. My question is: Do I have to merge these files first before I can use them with leaflet or can I use the data from the csv separately in leaflet? And if I have to merge them first, how do I merge these files and keep the polygons in the result, because if I use the function merge, the result will not be a SpatialPlolygonsDataframe.

My code

library(viridis)
library(geojsonio)
library(leaflet)


setwd('H:/Mijn documenten/R')

Neighborhoods <- geojsonio::geojson_read("Buurten/BuurtGrHTB2017_2.geojson",
                                      what = "sp")

deData <- read.csv(file="Buurten/Gegevens.csv", header=TRUE, sep=";")

MapData <- merge(Neighborhoods,deData,by='BU_CODE')

pal <- colorNumeric("viridis", domain = NULL, reverse=TRUE)

leaflet(MapData) %>%
  addTiles() %>%
  addPolygons(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 1, fillColor=~pal(ifelse(P_GEHUWD<0,NaN,P_GEHUWD))) %>%
  addLegend(pal = pal, values = ~(ifelse(P_GEHUWD<0,NaN,P_GEHUWD)), title="Aantal Inwoners", opacity = 1.0)

kara
  • 3,205
  • 4
  • 20
  • 34
MacMax
  • 35
  • 1
  • 5

1 Answers1

2

I recommend using the sf-package. It's the latest generation of spatial data manipulation in R and easier to handle.

library(sf)
library(tidyverse)
library(geojsonsf)


Neighborhoods  <- geojson_sf('H:/Mijn documenten/R/Buurten/BuurtGrHTB2017_2.geojson')


deData <- read.csv(file='H:/Mijn documenten/R/Buurten/Gegevens.csv', header=TRUE, sep=";")

inner_join(Neighbourhoods, deData, by = 'BU_CODE') -> MapData 

or without dplyr

MapData <- merge(Neighbourhoods, deData, by = 'BU_CODE')

From there you are able to do whatever you want with leaflet

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
  • Thanx, I will try your solution – MacMax Apr 17 '19 at 12:31
  • Again thanx a lot, I used your solution and it works, I had to add one extra library, "geojsonsf" to make to complete it – MacMax Apr 17 '19 at 13:14
  • Oh then I will include it in my answer. If the answer is correct you can hit the "accept" button, so others see what worked for you and you get reputation :-) – Humpelstielzchen Apr 17 '19 at 13:15
  • 1
    Thanks for using `geojsonsf` :). However, if the geojson is relatively small then `sf::st_read()` should be sufficient, without having to load `geojsonsf`. – SymbolixAU Apr 17 '19 at 22:33