gpt4 book ai didi

r - 通过R中的sf将经纬度序列转换为多边形

转载 作者:行者123 更新时间:2023-12-04 09:57:46 31 4
gpt4 key购买 nike

我有五个经度和纬度形成这样的形状。

df <- c(order=1:5,
lon=c(119.4,119.4,119.4,119.5,119.5),
lat=c(-5.192,-5.192,-5.187,-5.187,-5.191))

我如何使用 sf 轻松地将它们转换为 sf 多边形数据框这样的包?
## Simple feature collection with 1 feature and 0 fields
## geometry type: POLYGON
## dimension: XY
## bbox: xmin: 119.4 ymin: -5.192 xmax: 119.5 ymax: -5.187
## epsg (SRID): 4326
## proj4string: +proj=longlat +datum=WGS84 +no_defs
## geometry
## 1 POLYGON ((119.4 ...

最佳答案

我看到这个问题出现在搜索结果中,所以我想我会在 sf 中提供一种更灵活的创建多边形的方法来自一系列 latlon坐标。st_as_sf有争论 coords它将获取作为数据框中坐标列给出的点,并将这些列转换为 sf POINT几何形状。然后,因为sfdplyr 配合良好,我们可以st_combine积分变成MULTIPOINTst_cast转换为 POLYGON .与 st_polygon 的“手动”构造相比,这样做的好处是我们不必仔细考虑关闭环或传递给构造函数的嵌套列表的正确级别,并且如果我们在一组坐标中有多个多边形,我们可以使用group_by一次创建所有多边形。
注意从技术上讲,您可以使用 do_union=FALSE 来做到这一点。内部 summarise ,但我觉得这个语法更清晰一点,更像普通的 summarise .

df <- data.frame(
lon = c(119.4, 119.4, 119.4, 119.5, 119.5),
lat = c(-5.192, -5.192, -5.187, -5.187, -5.191)
)
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
polygon <- df %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON")
polygon
#> Simple feature collection with 1 feature and 0 fields
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 119.4 ymin: -5.192 xmax: 119.5 ymax: -5.187
#> epsg (SRID): 4326
#> proj4string: +proj=longlat +datum=WGS84 +no_defs
#> geometry
#> 1 POLYGON ((119.4 -5.192, 119...

plot(polygon)

创建于 2018-10-05 由 reprex package (v0.2.0)。

关于r - 通过R中的sf将经纬度序列转换为多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383990/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com