Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manually parsing geojson into a dataframe

I would like to work step by step to convert a .geojson into a tibble (or dataframe).

Here’s a minimalistic geojson example which I stored in a file called test.geojson (note that the geometry field is null but this does not matter here) :

{"type": "FeatureCollection",
  "features": [
    { "type": "Feature", "properties": { "VAR_1": 31,"VAR_2": "abc","VAR_3": 255 }, "geometry" : null },
    { "type": "Feature", "properties": { "VAR_1": 23,"VAR_2": "def","VAR_3": 876 }, "geometry" : null }
    ]}

Desired result (here assuming that geometry is filled with two coordinates instead of being null)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# A tibble: 2 x 3
  VAR_1 VAR_2 VAR_3 geometry
  <dbl> <chr> <dbl> <list>
1    31 abc     255 <dbl [2]>
2    23 def     876 <dbl [2]>

I’d partiularly like a {tidyverse} based solution. What I’ve been trying for now is iterate through each features to try and build a dataframe but I can’t find a way to nicely add the geometry field :

# Read geojson
js <- jsonlite::read_json("test.geojson") 

# Iterate through each features ... 
map_dfr(1:length(js$features), .f = function(i){
  
  df <- js$features[[i]]$properties # this works but only importing VAR_1, VAR_2, VAR_3
 
  df |> mutate(geometry = js$features[[i]]$geometry) # this does not work
  
})

Note : One could use {geojsonsf} to import this directly as sf object with sf <- geojsonsf::geojson_sf("test.geojson") but I want to do it step by step, ending up on a tibble and understanding what I’m doing.

Thanks a lot for helping !

>Solution :

Assuming the data is something like this:

x <- '{"type": "FeatureCollection",
  "features": [
    { "type": "Feature", "properties": { "VAR_1": 31,"VAR_2": "abc","VAR_3": 255 }, "geometry" : [-74.0060, 40.7128]},
    { "type": "Feature", "properties": { "VAR_1": 23,"VAR_2": "def","VAR_3": 876 }, "geometry" : [-74.0060, 40.7128]}
    ]}'

You can do this:

library(tidyverse)

jsonlite::fromJSON(x)$features |>
  as_tibble() |>
  select(properties, geometry) |>
  unnest(properties)

# Output:
# A tibble: 2 × 4
  VAR_1 VAR_2 VAR_3 geometry 
  <int> <chr> <int> <list>   
1    31 abc     255 <dbl [2]>
2    23 def     876 <dbl [2]>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading