Fastest way to determine what shapefile polygon a point is in?

I have a dataframe of points and a shapefile with about 2000 named polygon. I'm trying to determine which polygon each point is in, but I'm having a difficult time. I tried this solution from google:

y22Sample$region = apply(samplell, 1, function(row) { palner = st_transform(shape, 2163) coords = as.data.frame(matrix(row, nrow=1, dimnames = list("", c("x", "y")))) pnt_sf = st_transform(st_sfc(st_point(row),crs = 4326), 2163) palner[which(st_intersects(pnt_sf, palner, sparse = FALSE)), ]$NAME_1 })

But this isn't completing, even for just a sample of 1000 points (after running for over 1 hour). This method will be absolutely impossible for my full dataframe of over 5 million points.

Does anybody else have a good solution? I would appreciate some help.

Welcome. Does this do what you want?

library(sf)

# data from sf package
st_intersection(nz_height, nz)

It adds the polygon info to the point. You could just include the columns that you wanted before you intersected to make it cleaner.

A similar problem has been raised recently on another site; have look at the example over there R function to label a point contained within a polygon - Stack Overflow

I have a good experience with sf::st_join() for point-in-polygon operations. As long as your datasets fit in memory. Just be sure to check that the coordinate reference systems are aligned.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.