我想计算数据集每行中显示的点和线之间的距离。 下面是我拥有的数据的一个小例子
point_id point_lat point_lon geometry line_id
1 25417 47.2085 6.23435 LINESTRING (5.71922 47.01, ... 1203
2 21475 47.0499 5.21145 LINESTRING (5.13693 46.9399... 1120
dput(data)
structure(list(point_id = c("25417", "21475"), point_lat = c(47.2084948390554,
47.049888920732), point_lon = c(6.23434636370335, 5.21144989212184
), geometry = structure(list(structure(c(5.7192239291661, 5.72408115442851,
47.0100084570507, 47.0055943850847), .Dim = c(2L, 2L), class = c("XY",
"LINESTRING", "sfg")), structure(c(5.13693475951681, 5.14588443111801,
46.9399237940937, 46.9393947420422), .Dim = c(2L, 2L), class = c("XY",
"LINESTRING", "sfg"))), class = c("sfc_LINESTRING", "sfc"), precision = 0, bbox = structure(c(xmin = 5.13693475951681,
ymin = 46.9393947420422, xmax = 5.72408115442851, ymax = 47.0100084570507
), class = "bbox"), crs = structure(list(input = "EPSG:4326",
wkt = "GEOGCRS[\"WGS 84\",\n ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n MEMBER[\"World Geodetic System 1984 (Transit)\"],\n MEMBER[\"World Geodetic System 1984 (G730)\"],\n MEMBER[\"World Geodetic System 1984 (G873)\"],\n MEMBER[\"World Geodetic System 1984 (G1150)\"],\n MEMBER[\"World Geodetic System 1984 (G1674)\"],\n MEMBER[\"World Geodetic System 1984 (G1762)\"],\n MEMBER[\"World Geodetic System 1984 (G2139)\"],\n ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n LENGTHUNIT[\"metre\",1]],\n ENSEMBLEACCURACY[2.0]],\n PRIMEM[\"Greenwich\",0,\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n CS[ellipsoidal,2],\n AXIS[\"geodetic latitude (Lat)\",north,\n ORDER[1],\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n AXIS[\"geodetic longitude (Lon)\",east,\n ORDER[2],\n ANGLEUNIT[\"degree\",0.0174532925199433]],\n USAGE[\n SCOPE[\"Horizontal component of 3D system.\"],\n AREA[\"World.\"],\n BBOX[-90,-180,90,180]],\n ID[\"EPSG\",4326]]"), class = "crs"), n_empty = 0L),
line_id = c(1203L, 1120L)), row.names = c(NA, -2L), class = "data.frame")
我想计算对应线的点之间的距离。所以点 25417 和线 1203 之间的距离以及 21475 和线 1120 之间的距离。
谢谢您的帮助
这是一个有点不常见的结构,因为它带有
geometry
/ sfc 列,但 sf
类属性未设置或被有意删除(即 sf
方法不能在框架本身上使用)
我们可以采用这样的方法,同时保持结果为
data.frame
:
sf
点对象,假设坐标为WGS84(y
参数)geometry
列(x
参数)中的行与生成的 sf
对象 (y
)library(sf)
data$dist_m <- st_distance(x = data$geometry,
y = st_as_sf(data, coords = c("point_lon", "point_lat"), crs = "WGS84"),
by_element = TRUE)
data
#> point_id point_lat point_lon geometry line_id
#> 1 25417 47.20849 6.234346 LINESTRING (5.719224 47.010... 1203
#> 2 21475 47.04989 5.211450 LINESTRING (5.136935 46.939... 1120
#> dist_m
#> 1 44725.65 [m]
#> 2 13254.55 [m]
创建于 2023-09-28,使用 reprex v2.0.2