How to preserve IDs with geojsonio package?

87 Views Asked by At

I am trying to read a topoJSON file generated with geojsonio package: https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-raw/r15_arica_y_parinacota.json

Here's a preview of the relevant part on first entry in that file:

{"type":"Topology", ... , "id":295,"properties":{"comuna":"Arica","id":295}} ...

To import I run:

r15 <- "https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-raw/r15_arica_y_parinacota.json"
r15 <- geojsonio::topojson_read(r15)

And then to convert back to topoJSON I run:

geojsonio::topojson_json(r15)

Which returns:

{"type":"Topology", ... , "id":0,"properties":{"id":"295","comuna":"Arica"}} ...

Being that id=0 wrong unless it's me, as it should be id=295 from the JSON I am reading.

How can I be sure that I am reading and writing to JSON in a correct way?

2

There are 2 best solutions below

0
On

Thanks @sckott

Your example gave me a simple idea that solves this. Being my original intention to visualize a map, here's the fully reproducible example of what worked. I decided to create a new id column in the tibble that I will use with the topoJSON data:

if (!require("pacman")) { install.packages("pacman") }
pacman::p_load(geojsonio, dplyr)
pacman::p_load_gh("pachamaltese/d3plus", "pachamaltese/chilemaps")

# data to visualize on a map

data3 <- tibble(
  id = c(307, 295, 302, 331),
  comuna = c("General Lagos", "Arica", "Camarones", "Putre"),
  valor = c(400,300,200,100)
) %>%
  arrange(id) %>%
  mutate(id2 = row_number() - 1) # trick to match modified JSON "ids" after reading from GH

# visualize using SpatialPolygonsDataFrame

r15 <-  subset(chilemaps::comunas, region_id == 15)

d3plus() %>%
  d3p_data(data3) %>%
  d3p_map(coords = geojsonio::topojson_json(r15), text = "comuna", tooltip = "valor") %>%
  d3p_id(c("id")) %>%
  d3p_colour("valor")

# visualize using topoJSON read from GitHub

r15_2 <- "https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-json/r15_arica_y_parinacota.json"
r15_2_out <- geojsonio::topojson_read(r15_2)

d3plus() %>%
  d3p_data(data3) %>%
  d3p_map(coords = geojsonio::topojson_json(r15_2_out), text = "comuna", tooltip = "valor") %>%
  d3p_id(c("id2")) %>% # here I use id2 instead of id
  d3p_colour("valor")
3
On

The ids are getting mangled by sp pkg I think

library(geojsonio)
r15 <- "https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-raw/r15_arica_y_parinacota.json"
out <- topojson_read(r15)
x <- topojson_list(out)
vapply(x$objects$foo$geometries, "[[", 1, "id")
#> [1] 0 1 2 3
vapply(x$objects$foo$geometries, function(z) z$properties$id, "")
#> [1] "295" "302" "307" "331"

We use sp internally in topojson_read.

So the "295" "302" "307" "331" are getting nested inside of other ids.

If we do

s <- sf::st_read(r15)
topojson_list(zz)

I think that gets what you want