我正在尝试读取使用geojsonio包生成的topoJSON文件:https://raw.githubusercontent.com/pachamaltese/chilemaps/master/data-raw/r15_arica_y_parinacota.json
下面是该文件中第一个条目的相关部分的预览:
{"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?
发布于 2019-01-29 14:42:08
我觉得I被sp包弄坏了
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”被嵌套在其他ids中。
如果我们这样做了
s <- sf::st_read(r15)
topojson_list(zz)我想这就得到了你想要的
发布于 2019-01-29 23:15:28
谢谢@sckott
你的例子给了我一个简单的想法来解决这个问题。我的初衷是可视化一张地图,这里是一个完全可重现的例子。我决定在tibble中创建一个新的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")https://stackoverflow.com/questions/54413792
复制相似问题