I´m having trouble converting coordinates data to sf format. I exported a csv file from QGIS with attributes of several political units with their respective coordinates. Because I'm working with polygons I exported the csv file from QGIS as WKT (MultiPolygon Z).
However, when I import the csv file into R, it takes the coordinate column as a character instead of sfg.Therefore, I use the st_as_sf function, but it returns the following error:
all_sf <- all2 %>% st_as_sf(wkt = "geometry", crs = 4326)
OGR: Corrupt data Error: OGR error
OBJECTID | Distrito | Año | geometry |
---|---|---|---|
13939 | Alberdi | 1996 | MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-6... |
13939 | Alberdi | 1997 | MULTIPOLYGON Z (((-60.32233429 -34.7621421809999 0,-6... |
(1000 rows more)
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 ...
I believe there is either an issue with:
sp
rather than sf
misinterpreting your geometry values as strings. That's because this works:
library(rnaturalearth)
library(dplyr)
library(sf) # GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
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"
One solution is to see if exporting your QGIS data as a shapefile, then importing it into R solves your issue. First, in QGIS:
Next, import your shapefile data into R:
all_sf <- st_read("path/to/your/shapefile.shp") %>%
st_set_crs(4326) # If your data do not have a CRS already
If this does not work, then at least you can confirm the error lies with your original QGIS data or your libraries and can start debugging from there.