I've a GeoJson file for Peru and it's states (Departamentos in Spanish).
I can plot Peru's states using leaflet, but as the GeoJson file has not all the data I need, I'm thinking of converting it to a data.frame adding the columns of data I need then return it to GeoJson format for plotting.
Data: You can donwload the GeoJson data of Perú from here:
This is the data I'm using and I need to add it a Sales Column with a row for every state ("NOMBDEP" - 24 in total)
library(leaflet)
library(jsonlite)
library(dplyr)
states <- geojsonio::geojson_read("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson", what = "sp")
I thought of using "jsonlite" package to transform "GeoJson" to a data frame, but getting this error:
library(jsonlite)
states <- fromJSON(states)
Error: Argument 'txt' must be a JSON string, URL or file.
I was expecting that after having a data frame I could be able to do something like:
states$sales #sales is a vector with the sales for every department
states <- toJson(states)
You can use library(geojsonsf)
to go to and from GeoJSON and sf
library(geojsonsf)
library(sf) ## for sf print methods
states <- geojsonsf::geojson_sf("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson")
states$myNewValue <- 1:nrow(states)
geo <- geojsonsf::sf_geojson(states)
substr(geo, 1, 200)
# [1] "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{\"COUNT\":84,\"FIRST_IDDP\":\"01\",\"HECTARES\":3930646.567,\"NOMBDEP\":\"AMAZONAS\",\"myNewValue\":1},\"geometry\":{\"type\":\"Polygon\",\"coordinat"
.
You can see myNewValue
is in the GeoJSON
You don't need to convert back and forth, you can just add another column to the states
SPDF:
states <- geojsonio::geojson_read("https://raw.githubusercontent.com/juaneladio/peru-geojson/master/peru_departamental_simple.geojson", what = "sp")
states$sales <- abs(rnorm(nrow(states), sd=1000))
plot(states, col=states$sales)
Yields this image:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With