本文介绍了通过R中的sf将经纬度序列转换为多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have five longitude and latitude that form a shape like this.

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 多边形数据框?

How could I easily convert them into an sf polygon data frame using sf package like this?

## 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 ...

推荐答案

我看到这个问题出现在搜索结果中,所以我想我会提供一个更灵活的方法来在 sfsf 中创建多边形code> 来自一系列 latlon 坐标.

I saw that this question is coming up in search results, so I thought I'd provide a more flexible method of creating polygons in sf from a series of lat and lon coordinates.

st_as_sf 有一个参数 coords ,它将获取作为数据框中坐标列给出的点,并将这些列转换为 sf POINT 几何形状.然后,因为 sfdplyr 配合良好,我们可以将点 st_combine 转化为 MULTIPOINTst_cast 转换为 POLYGON.与手动"相比使用 st_polygon 构造,这样做的好处是我们不必仔细考虑关闭环或传递给构造函数的嵌套列表的正确级别,并且如果我们有超过一组坐标中的一个多边形,我们可以使用 group_by 一次创建所有多边形.

st_as_sf has an argument coords that will take points given as coordinate columns in a data frame and convert those columns to sf POINT geometries. Then, because sf works well with dplyr, we can st_combine the points into a MULTIPOINT and st_cast to convert to POLYGON. Compared to "manual" construction with st_polygon, this has the advantage that we don't have to think so carefully about closing the ring or about the right level of nested lists to pass to the constructor, and that if we have more than one polygon in a set of coordinates we can use group_by to create all the polygons at once.

注意从技术上讲,您可以使用 summarise 中的 do_union=FALSE 来做到这一点,但我认为这种语法更清晰,更类似于普通的 summarise.

N.B. Technically you can do this with do_union=FALSE inside of summarise, but I think that this syntax is a bit clearer and more similar to normal 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)

reprex 包 (v0.2.0) 于 2018 年 10 月 5 日创建.

Created on 2018-10-05 by the reprex package (v0.2.0).

这篇关于通过R中的sf将经纬度序列转换为多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 00:26