Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: From GeoJson to DataFrame?

Tags:

r

geojson

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)
like image 440
Omar Gonzales Avatar asked Aug 17 '18 04:08

Omar Gonzales


2 Answers

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

like image 130
SymbolixAU Avatar answered Sep 29 '22 08:09

SymbolixAU


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: enter image description here

like image 35
Stedy Avatar answered Sep 29 '22 08:09

Stedy