我在将坐标数据转换为 sf 格式时遇到问题。我从 QGIS 导出了一个 csv 文件,其中包含几个政治单位的属性及其各自的坐标。因为我正在处理多边形,所以我将 csv 文件从 QGIS 导出为 WKT (MultiPolygon Z)。
但是,当我将csv文件导入到R中时,它将坐标列作为字符而不是sfg。因此,我使用st_as_sf函数,但它返回以下错误:
all_sf <- all2 %>% st_as_sf(wkt = "geometry", crs = 4326)
OGR: Corrupt data Error: OGR error
对象ID | 区 | 阿诺 | 几何 |
---|---|---|---|
13939 | 阿尔伯迪 | 1996 | 多多边形 Z (((-60.32233429 -34.7621421809999 0,-6... |
13939 | 阿尔伯迪 | 1997 | 多多边形 Z (((-60.32233429 -34.7621421809999 0,-6... |
(1000行以上)
str(all2)'data.frame': 1058 obs. of 5 variables:
$ OBJECTID : chr "13939" "13939" "13939" "13939" ...
$ Distrito : chr "Alberti" "Alberti" "Alberti" "Alberti" ...
$ Año : chr "1996" "1997" "1998" "1999" ...
$ toneladas: num 0 0 0 0 0 0 0 0 0 0 ...
$ geometry : chr "MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-60.2506828309999 -34.8179740909999 0,-60.2398338319999 -34."| truncated "MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-60.2506828309999 -34.8179740909999 0,-60.2398338319999 -34."| truncated "MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-60.2506828309999 -34.8179740909999 0,-60.2398338319999 -34."| truncated "MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-60.2506828309999 -34.8179740909999 0,-60.2398338319999 -34."| truncated ...
我相信您的数据存在问题,而不是
sf
将您的几何值误解为字符串。那是因为这有效:
library(rnaturalearth)
library(dplyr)
library(sf)
packageVersion("rnaturalearth")
# [1] ‘1.0.1’
packageVersion("dplyr")
# [1] ‘1.1.4’
packageVersion("sf")
# [1] ‘1.0.15’
# Create sample csv file
sf_csv <- ne_countries(returnclass = 'sf') %>%
mutate(sfid = 1:n()) %>%
select(sovereignt, sfid) %>%
st_write(., "sf_csv.csv",
append = FALSE,
layer_options = "GEOMETRY=AS_WKT")
# Writing layer `sf_csv' to data source `sf_csv.csv' using driver `CSV'
# options: GEOMETRY=AS_WKT
# Writing 177 features with 2 fields and geometry type Multi Polygon.
# Import sample csv
sf_csv <- read.csv("sf_csv.csv")
# Create sf object from sf_csv
all_sf <- sf_csv %>% st_as_sf(wkt = "WKT", crs = 4326)
class(all_sf)
# [1] "sf" "data.frame"
一种解决方案是查看将 QGIS 数据导出为 shapefile,然后将其导入 R 是否可以解决您的问题。首先,在QGIS中:
接下来,将 shapefile 数据导入到 R 中:
all_sf <- st_read("path/to/your/shapefile.shp") %>%
st_set_crs(4326) # If your data do not have a CRS already
如果这不起作用,那么至少您可以确认错误出在您的原始 QGIS 数据上,并可以从那里开始调试。