Search code examples
rr-sfhexagonal-tilesgeojsonio

Export SpatialPolygonsDataFrame as geojson or topojson in R


I am trying to convert a geojson of London local authorities into a hex cartogram where each hexagon represents one local authority. It works in R but when I try to export the generated hexgrid as geojson or topojson I get the following error:

Error in sp::SpatialPolygonsDataFrame(polys, data = input@data) : 
  row.names of data and Polygons IDs do not match

Here's the code. I am using geogrid to generate the grid and geojsonio to export the generated dataframe to geojson or topojson:

library(geogrid)
library(geojsonio) # version 0.9.0

df <- read_polygons(system.file("extdata", "london_LA.json", package = "geogrid"))
# you can get the json file from here: https://github.com/jbaileyh/geogrid/blob/master/inst/extdata/london_LA.json

# Set arguments for plot
par(mfrow = c(2, 3), mar = c(0, 0, 2, 0))

# Hexagonal grid with 6 seeds
for (i in 1:3) {
  grid_hexagon <- calculate_grid(shape = df, learning_rate = 0.05, grid_type = "hexagonal", seed = i)
  plot(grid_hexagon, main = paste("Seed", i, sep = " "))
}

# Square grid
for (i in 1:3) {
  grid_square <- calculate_grid(shape = df, grid_type = "regular", seed = i)
  sp::plot(grid_square, main = paste("Seed", i, sep = " "))
}

# Get a SpatialDataFrame from our desired grid
tmp <- calculate_grid(shape = df, grid_type = "hexagonal", seed = 3)
df_hex <- assign_polygons(df, tmp)

# And export to TopoJSON
topojson_write(df_hex, object_name = "local_authorities", file = "output/london_hex.json")

Any suggestions about how can I solve this issue? Also, I am interested in hearing about other approaches to generate hex cartograms giving a specific input file.

References: https://github.com/jbaileyh/geogrid


Solution

  • You can convert the SpatialPolygonsDataFrame to sf, and then write to GeoJSON file with st_write:

    library(sf)                                                                                                                               
    df_hex = st_as_sf(df_hex)                                                                                                                 
    st_write(df_hex, "df_hex.geojson") 
    

    Here is the result in QGIS:

    enter image description here