I have a series with shapefiles (not created by me) that I want to merge together. I am opening them with the terra
package in R as a list of SpatVectors. However, when I try to merge them, I get the following error message:
Error: [vect] all SpatVectors must have the same geometry type
I found out (by running geomtype()
) that one of my SpatVectors has geometry type "null"
, while the other ones are "polygons"
. How can I assign the same geometry type ("polygons") to the SpatVector without one?
I have tried the below, but none of them worked:
null_geometry_type_SpatVector <-
vect("null_geometry_type_SpatVector.shp", type="polygons")
geomtype(null_geometry_type_SpatVector) <-
geomtype(polygons_geometry_type_SpatVector)
Where polygons_geometry_type_SpatVector
refers to a SpatVector I have with the correct geometry type.
geomtype(null_geometry_type_SpatVector) <- "polygons"
UPDATE:
Following an answer below, I have tried:
i <- emptyGeoms(null_geometry_type_SpatVector)
null_geometry_type_SpatVector_cleaned <- null_geometry_type_SpatVector[!i]
The commands run, but I am not sure what to do next. My goal is to be able to merge null_geometry_type_SpatVector
with the other SpatVectors I have in my list (each SpatVector is a county in the US and merged together they form a state). So I believe I have to assign geometry type "polygons"
to null_geometry_type_SpatVector_cleaned
so I am able to merge it with the other SpatVectors and plot the merged SpatVector, but I still don't know how to do it. Any suggestions?
UPDATE 2:
The file that I am using that had NULL geometry is this one.
Thank you for providing an example file. With that file, I get
x <- vect("clu_public_a_ne165.shp")
geomtype(x)
#[1] "null"
You can fix that with
x <- na.omit(x, geom=TRUE)
geomtype(x)
#[1] "polygons"
Or with
x <- vect("clu_public_a_ne165.shp")
i <- emptyGeoms(x)
x <- x[-i]
geomtype(x)
#[1] "polygons"
And then proceed with x
.
This does mean that you lose the records that do not have an associated geometry.
If you do not want that to happen, you can use the terra 1.7-32. This is currently the development version that you can install with
install.packages('terra', repos='https://rspatial.r-universe.dev')
With that version you should not get an error message at all when you use rbind
(that is what I assume you are using).