TransWikia.com

Error message when joining two dataframes with sf -Error: y should be a data.frame; for spatial joins, use st_join

Geographic Information Systems Asked by Adam G on April 28, 2021

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).

library(sf)
library(dplyr)


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```


One Answer

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.

Answered by dieghernan on April 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP