You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中基于SFC坐标查找行号,提取对应列数值的方法

问题:根据经纬度查找sf数据框对应行号

我刚接触R中的大地测量数据,若表述有误还请见谅。我有一个数据集,包含存储SFC点的geometry列和IntersectingPoints列:

IntersectingPoints             geometry
<list>                      <POINT [°]>
<int [4,415]>      (144.9179 -45.59569)
<int [3,388]>     (5.740768 49.15625)
<int [6,214]>        (2.18701 52.80779)
<int [7,948]>       (3.108628 50.58135)
<int [2,298]>      (-96.77081 37.37828)

我希望输入x、y值来查找对应的行号,进而提取IntersectingPoints列的对应值。我编写的代码如下:

x = 144.9179
y = 45.59569
point_ref=st_point(c(x,y))
which(pt$geometry == point_ref)

我预期该代码会输出第一行,但实际无法运行,推测是因为geometry列属于列表类型。得到的错误信息如下:

Error in which(pt$geometry == point_ref) : 
  'list' object cannot be coerced to type 'double'
In addition: Warning messages:
1: In which(pt$geometry == point_ref) :
  Incompatible methods ("Ops.sfc", "Ops.sfg") for "=="
2: In pt$geometry == point_ref :
  longer object length is not a multiple of shorter object length

请问如何实现输出对应行号?

解决方案

直接用==比较sfc类型的geometry列和单个sfg点是不兼容的,sf包提供了专门的空间匹配函数来处理这类需求,推荐两种方法:

方法1:使用st_equals函数

st_equals可判断空间对象是否完全相等,返回逻辑矩阵,用它筛选行即可:

library(sf)

x = 144.9179
y = -45.59569  # 注意原数据中y为负值,原代码写的正值会导致匹配失败
# 确保参考点的坐标系与原数据一致
point_ref = st_point(c(x, y)) %>% st_sfc(crs = st_crs(pt))

# 获取匹配的行号
match_rows = which(st_equals(pt$geometry, point_ref, sparse = FALSE))
print(match_rows)

方法2:提取坐标后数值比较

若不需要严格空间匹配,可直接提取geometry列的坐标进行数值对比:

# 提取geometry列的x、y坐标
pt$x = st_coordinates(pt$geometry)[,1]
pt$y = st_coordinates(pt$geometry)[,2]

# 用极小误差范围避免浮点精度问题,查找匹配行号
match_rows = which(abs(pt$x - x) < 1e-6 & abs(pt$y - y) < 1e-6)
print(match_rows)

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:02:43