In R, I'm trying to count the number of points which fall within a buffer around polygons and add the count result to the original shapefile from which the polygon file was created. I've followed the answer provided by @Guzmán from this question: Counting number of points in polygon using R?. Everything works fine until it comes to adding the result to the original shapefile, which I want to do based on the attribute "ID", i.e. not a spatial join. I get the error message "Error: y should be a data.frame; for spatial joins, use st_join" even though y is a dataframe (at least it is according to is.data.frame).


OrigPolys <- st_read("OrigPolys.shp") #Load polygons
Points <- st_read("Points.shp") #Load points
NewPolys <- subset(OrigPolys, X1 != 'NA') #Subset required polygons
Buffer <- st_buffer(NewPolys, 5000) #Create buffer NewPolys
inter <- st_intersection(Buffer, Points) #Find points in NewPolys
int_count <- inter %>% 
  group_by(ID) %>% 
  count() #Count number of Points in Buffer
as.data.frame(int_count) #Convert to df (not sure if this is required as is.data.frame = T whether included or not)
OrigPolys_Pts <- left_join(OrigPolys, int_count, by = "ID") #Join count to OrigPolys based on "ID" attribute```

  • Well, an sf object can be both a data.frame and a spatial object. Looking at class(x) is a more reliable way to look at object classes. Have you tried following the advice in the error, which is very rare for R, and tried using st_join. If you are, in fact, dealing with two spatial objects it should return what you are after. May 31, 2021 at 0:13

1 Answer 1


Better Try int_count=st_drop_geometry(int_count) before performing the join. Geometries are sticky in sf, meaning that they would be in the object unless you explicitly erase them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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