Search code examples
rgeojsonropensci

Convert data to geojson error


I am trying to use the geojsonio package to write some geojson files from data.frames pulled from some other R packages.

library(ggplot2)
library(geojsonio)
us_state <- map_data('state')

geojson_write(us_state, 
              geometry="polygon", 
              grouping="group", 
              file="path/file.geojson")

The problem I'm having is with the geometry=polygon argument. I get the following error:

Error in .subset2(x, i, exact = exact) : 
  attempt to select less than one element in integerOneIndex

When geometry=point it works fine, but then of course I have just a million separate points instead of state polygons in the geojson file.

Any thoughts?

Edit:

I can get a working geojson file if I use file<-geojson_json(data.frame) first, then geojson_write(file)


Solution

  • You just need to use the right parameter name group, not grouping. Since the function has a ..., a wrong parameter name can be passed in and not throw any errors/etc.

    library(ggplot2)
    library(geojsonio)
    us_state <- map_data('state')
    geojson_write(us_state, 
              geometry = "polygon", 
              group = "group", 
              file = "file.geojson")
    
    #> {
    #> "type": "FeatureCollection",
    #>                                                                                 
    #> "features": [
    #> { "type": "Feature", "id": 0, "properties": { "dummy": 0.000000 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -87.462005615234375, 30.389680862426758 ], [ -87.484931945800781, 30.372491836547852 ], [ -87.525032043457031, 30.372491836547852 ], [ -87.53076171875, 30.332386016845703 ], [ -87.570869445800781, 30.326654434204102 ], [ -87.588058471679688, 30.326654434204102 ], [ -87.593788146972656, 30.309467315673828 ], [ -87.593788146972656, 30.286548614501953 ], [ -8
    #> ... cutoff