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

如何在R中使用sf包旋转网格?解决多边形未闭合报错

解决sf网格旋转时的“polygons not (all) closed”报错问题

你的问题出在spatialEco::rotate.polygon对sf格式网格的兼容性不足——这个函数更适配sp对象,处理sf网格多边形时容易触发闭合性校验失败的报错。直接用sf原生的空间变换工具就能解决,不用绕远路。

修复方案:替换rotate.polygon为sf原生旋转方法

方法1:用st_rotate(sf >= 1.0-0版本支持)

直接调用st_rotate,指定旋转中心为原始xy点,所有网格会围绕中心点旋转,同时完整保留网格结构:

# 4) Rotate(替换原rotate.polygon代码)
# 获取旋转中心坐标
rotate_center <- st_coordinates(xy)[1,]
# 旋转网格,angle参数单位为度
grid_1ha_rotated <- st_rotate(grid_1ha, angle = 45, center = rotate_center)

# 查看旋转结果
ggplot() +
  geom_sf(data = grid_1ha_rotated$geometry, color = 'red') +
  geom_sf(data=cen_buffer, color='black') +
  geom_sf(data = xy$geometry, color = 'red')

方法2:手动构造旋转矩阵(兼容旧版sf)

如果你的sf版本较低不支持st_rotate,可以通过仿射变换矩阵实现旋转,原理是先把网格平移到原点、旋转,再平移回中心:

# 4) Rotate(手动构造旋转矩阵)
rotate_center <- st_coordinates(xy)[1,]
angle_rad <- 45 * pi / 180  # 角度转弧度
# 构造2D旋转矩阵
rotation_matrix <- matrix(
  c(cos(angle_rad), -sin(angle_rad), sin(angle_rad), cos(angle_rad)),
  nrow = 2, ncol = 2
)
# 执行平移-旋转-平移回位操作
grid_1ha_rotated <- grid_1ha %>%
  st_translate(-rotate_center) %>%
  st_affine(rotation_matrix) %>%
  st_translate(rotate_center)

# 可视化验证结果
ggplot() +
  geom_sf(data = grid_1ha_rotated$geometry, color = 'red') +
  geom_sf(data=cen_buffer, color='black') +
  geom_sf(data = xy$geometry, color = 'red')

为什么之前的尝试无效?

  • st_set_precision和st_make_valid用于修复拓扑无效问题,但你的报错本质是rotate.polygon对sf对象的适配缺陷,不是原始网格本身无效;
  • st_cast转换多边形类型也无法解决函数兼容性问题,核心矛盾不在多边形类型上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:16:26