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

在sf对象上使用dplyr::filter报错:vec_size()参数类型错误

问题原因与解决方案

原因

该错误源于vctrs 0.6.x版本对向量类型的检查逻辑收紧:dplyr 1.1.3依赖此版本的vctrs,而geojsonsf生成的sf对象中的sfc_POLYGON几何列,无法被新版vctrs的vec_slice函数识别为合法向量类型,导致filter操作在切片数据时失败。旧版本vctrs(0.5.x及以下)对sf对象的兼容性更宽松,因此在R 4.2+dplyr 1.1.1环境下可正常运行。

解决方法

方法1:使用sf包读取GeoJSON(推荐)

替换geojsonsf为官方sf包读取数据,它与新版dplyr/vctrs的兼容性更完善:

library(dplyr); library(sf)
orig <- st_read("downtowns-original.geojson")

orig %>%
  filter(city == "San Francisco")

方法2:降级vctrs版本

将vctrs降级至0.5.x版本(如0.5.2),恢复旧的兼容性逻辑:

# 卸载当前vctrs版本
remove.packages("vctrs")
# 安装指定旧版本
install.packages("vctrs", version = "0.5.2", repos = "https://cran.r-project.org")

注意:降级可能影响其他依赖vctrs新版本的R包,需评估后操作。

方法3:手动转换后过滤

先将sf对象转为普通data.frame完成过滤,再重新组合为sf对象:

library(dplyr); library(geojsonsf); library(sf)
orig <- geojson_sf("downtowns-original.geojson")

# 提取几何列并保存
geom_data <- orig$geometry
# 转换为data.frame执行过滤
filtered_df <- orig %>%
  as.data.frame() %>%
  filter(city == "San Francisco")
# 重新构建sf对象
filtered_sf <- st_sf(filtered_df, geometry = geom_data[rownames(filtered_df)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:47:54