我想将数据作为SF对象从小叶 map 导入R中. map 是这个网站:https://erickgn.github.io/mapafc/我也有来自 map 的HTML,如下所示:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html.
我想将数据作为SF对象从小叶 map 导入R中. map 是这个网站:https://erickgn.github.io/mapafc/我也有来自 map 的HTML,如下所示:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html.
我还有来自 map 的HTML,如下所示:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html.
那你就什么都有了.要么将页面保存在本地,要么使用xml2
包将其废弃.如果您查看页面源代码,您可以找到类似以下内容:
geo_json_b75320e180b34bb88a8a9025dff8675e_add({"bbox": [-44.447264,
-23.03329, -41.6957233, -22.2949485],[...]
似乎这就是您的特性,您可以使用SF::ST_READ或jsonlite
包来阅读它.
第一个JSON的一个小示例:
library(rvest)
url <- "https://raw.githubusercontent.com/erickgn/mapafc/main/index.html"
text <- html_text(read_html(url))
现在我们必须定位json和json前后的两个字符串
在这两者之间扮演一个角色.请注意+1, -22
--第一个是非常明显的,第二个是试图删除不必要的新行等等.
library(stringi)
st <- stri_locate_first_fixed(text, "geo_json_b75320e180b34bb88a8a9025dff8675e_add(")[2]+1
fi <- stri_locate_first_fixed(text, "geo_json_b75320e180b34bb88a8a9025dff8675e.bindTooltip(")[1]-22
json <- substring(text, st, fi)
最后,让我们将json转换为R对象:
jsonlite::fromJSON(json)
#> $bbox
#> [1] -44.44726 -23.03329 -41.69572 -22.29495
#>
#> $features
#> bbox
#> 1 -43.59792, -22.82906, -43.58869, -22.82160
#> 2 -43.38023, -22.96123, -43.37173, -22.95453
#> 3 -43.50182, -23.03329, -43.49279, -23.02227
#> 4 -43.29931, -22.99099, -43.29163, -22.98606
[...]
您可以对下一个json重复类似的步骤.
阅读sf
个包裹:
library(sf)
a <- st_read(json)
#> Reading layer `OGRGeoJSON' from data source
#> [...]
#> using driver `GeoJSON'
#> Simple feature collection with 249 features and 16 fields
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: -44.44726 ymin: -23.03329 xmax: -41.69572 ymax: -22.29495
#> Geodetic CRS: WGS 84
plot(a$geometry)
由reprex package(v2.0.1)于2022年2月15日创建
向您致敬, 格泽戈尔茨