首页 > 解决方案 > 使用 sf 在 R 中将几何从两个坐标转换为三个坐标

问题描述

我有两个带有 sf 几何的数据框,其中一个有两个坐标,另一个有三个坐标,即一个坐标基于 c(1,2),另一个基于 c(3,4,0)。我想绑定这两个表但失败了,因为 R 是“期望三个坐标”。我想知道在 sf 中将几何从两个坐标转换为三个坐标的代码是什么?换句话说,我希望第一个坐标从 c(1, 2) 变为 c(1, 2, 0)。

非常感谢您提前提供帮助:)

标签: rsf

解决方案


如果我正确阅读了您的问题,您正在寻找一种将高度维度添加到您的一个数据集的方法。

为此,请考虑sf::st_zm()使用 drop = F 的函数(不删除 = 添加:)。

举个例子,考虑这个例子,建立在北卡罗来纳州的三个城市上(它与 {sf} 附带的 nc.shp 配合得很好)。

library(sf)
library(dplyr)

points <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x","y"), crs=4326)

points
# Simple feature collection with 3 features and 1 field
# Geometry type: POINT
# Dimension:     XY
# Bounding box:  xmin: -79.81944 ymin: 34.22333 xmax: -77.91222 ymax: 36.08
# Geodetic CRS:  WGS 84
#         name                   geometry
# 1    Raleigh POINT (-78.63333 35.76667)
# 2 Greensboro    POINT (-79.81944 36.08)
# 3 Wilmington POINT (-77.91222 34.22333)

pts_two <- points %>% 
  st_zm(drop = F, what = "Z")

pts_two    
# Simple feature collection with 3 features and 1 field
# Geometry type: POINT
# Dimension:     XYZ
# Bounding box:  xmin: -79.81944 ymin: 34.22333 xmax: -77.91222 ymax: 36.08
# z_range:       zmin: 0 zmax: 0
# Geodetic CRS:  WGS 84
#         name                       geometry
# 1    Raleigh POINT Z (-78.63333 35.76667 0)
# 2 Greensboro    POINT Z (-79.81944 36.08 0)
# 3 Wilmington POINT Z (-77.91222 34.22333 0)

推荐阅读