如何使用geojsonio软件包保留ID?

时间:2019-01-29 04:19:21

标签: r geojson topojson geojsonio

我正在尝试读取由geojsonio软件包:https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-raw/r15_arica_y_parinacota.json生成的topoJSON文件

以下是该文件中第一个条目的相关部分的预览:

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

要导入,我运行:

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

然后转换回topoJSON,我运行:

geojsonio::topojson_json(r15)

哪个返回:

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

除非是我,否则id=0是错误的,因为它应该是我正在读取的JSON中的id=295

如何确定我以正确的方式读写JSON?

2 个答案:

答案 0 :(得分:1)

我认为sp pkg破坏了ID

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"

我们在topojson_read内部使用sp。

因此,“ 295”,“ 302”,“ 307”,“ 331”正嵌套在其他ID的内部。

如果我们这样做

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

我想这就是您想要的

答案 1 :(得分:1)

感谢@sckott

您的示例为我提供了一个解决此问题的简单想法。作为我最初使地图可视化的初衷,以下是可以完全复制的有效示例。我决定在标题中创建一个新的id列,将其与topoJSON数据一起使用:

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")