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

导入含空间数据的CSV并转shapefile遇sf包报错求助

解决CDC/HHS医院数据POINT格式转Shapefile问题

问题原因

你使用sf_column_name报错是因为geocoded_hospital_address是字符串格式的WKT坐标,并非sf识别的几何列(sfc类型),因此需要先解析坐标格式,再转换为空间对象。


方法一:拆分经纬度列后转sf对象

适合你习惯的coords参数转换方式,先从字符串中提取经纬度数值:

library(tidyverse)
library(sf)

# 从POINT字符串中提取经纬度并转为数值型
hospital_data <- COVID_19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility %>%
  tidyr::extract(
    col = geocoded_hospital_address,
    into = c("longitude", "latitude"),
    regex = "POINT \\((-?\\d+\\.\\d+), (-?\\d+\\.\\d+)\\)",
    convert = TRUE
  )

# 转换为sf空间对象
hospital_sf <- hospital_data %>%
  st_as_sf(coords = c("longitude", "latitude"), crs = 4326)

# 导出为Shapefile
st_write(hospital_sf, "hospital_covid_capacity.shp", delete_layer = TRUE)

方法二:直接解析WKT字符串为几何列

无需拆分,直接将WKT字符串转为sf识别的几何对象:

library(sf)

# 解析WKT字符串为几何列,再转为sf对象
hospital_sf <- COVID_19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility %>%
  mutate(geometry = st_as_sfc(geocoded_hospital_address)) %>%
  st_as_sf(crs = 4326)

# 可选:过滤缺失几何的行
hospital_sf <- hospital_sf %>% filter(!is.na(geometry))

# 导出为Shapefile
st_write(hospital_sf, "hospital_covid_capacity.shp", delete_layer = TRUE)

注意事项

  • 若数据中存在空值或格式异常的geocoded_hospital_address,建议先通过filter(!is.na(geocoded_hospital_address))过滤后再处理;
  • st_write的delete_layer = TRUE参数用于覆盖已存在的同名Shapefile。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:15:49