I've got several shapefiles stored as geopackages and I want to merge all of them by using rbind. But unfortunately the geometry columns are namend differently as "geometry or "geom" and because of that I cannot rbind them. I can't see any reason why R is naming them differently. They're all pointshapes from the same research area and with the same crs and basically with same columnames (besides the geometry field for some reasons).

I've tried simply renaming the geomety column resulting in the error attr(obj, "sf_column") does not point to a geometry column as well as recreating the geometry column, but then it takes the same name every time.

But I found a workaround by renaming the columns and simply making the sf to a data frame and assigning the geometry afterwars. But it seems to me a bit hacky, so maybe do you have a more elegant way or maybe you can explain me the reasons for the different names in the first place.

My code:

wd <- setwd("filepath")

files <- list.files(path=wd, pattern="*.gpkg", full.names=TRUE, recursive=FALSE)
points_all <- data.frame()

for (i in c(1:length(files))) {
  file <- st_read(files[i])
  names(file) <- c("Value", "Coord")
  points_all <- rbind(points_all,file)
  points_all <- data.frame(points_all)

points_all <- st_set_geometry(points_all, points_all$Coord)

I've just written this which I think will safely rename the geometry column by changing the names element and then setting the geometry column with st_geometry - which will affect the sf_column attribute.

rename_geometry <- function(g, name){
    current = attr(g, "sf_column")
    names(g)[names(g)==current] = name

I don't see a function that will get the geometry column name, and the attribute is mentioned in the documentation so I think that is a safe way to get the name.

Use like this:

nc = rename_geometry(nc, "gyom")
plot(nc) # should work
names(nc) # shows "gyom"

I don't know if an sf method for rbind could be written that works by ignoring different names for the geometry columns and uses maybe the first one for the output, but it might be worth a feature request to the sf github.

  • It worked perfectly, thank you very much! I'll ask them if an implementation is possible. – David Feb 7 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.