How do I find the polygon nearest to a point in R?

前端 未结 2 661
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 23:29

I have a spatial points data frame and a spatial polygons data frame. For example, my polygons would be a polygon for each block in Manhattan. And the points are people, whi

2条回答
  •  忘掉有多难
    2020-12-08 23:57

    I'm way late to the party here, but I just found this thread, and for what it is worth, offer this suggestion. The nn2 function from the RANN package allows you to search (for closest points) over only some limited radius, which can save considerable time. My suggestion is to add points over the polygons, associate the points with the polygons, then search for the closest point. It looks like the gDistance method is faster when there are not many points, but the nn2 method scales up better to larger problems, because it searches a limited radius (of course, it will fail to find a match if no points are inside that radius, so the radius must be correctly chosen). I'm new at this, so this might not be optimal. It would be nice if gDistance would allow for a restricted search.

    ## Make some example  data
    set.seed(1)
    library(raster)
    library(rgdal)
    library(rgeos)
    library(RANN)
    library(spatialEco)
    
    p <- shapefile(system.file("external/lux.shp", package="raster"))
    
    ##  Project data into a planar coordinate system (here UTM zone 32)
    utmStr <- "+proj=utm +zone=%d +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0"
    crs <- CRS(sprintf(utmStr, 32))
    pUTM <- spTransform(p, crs)
    
    # the points of interest (all within some threshold distance of the polygons)
    ptsUTM <- spsample(gBuffer(pUTM,width=2000)-pUTM, n=10000, type="random")
    ## Plot to visualize
    plot(ptsUTM, pch=16, cex=.5,col="red")
    plot(pUTM, col=colorRampPalette(blues9)(12), add=TRUE)
    
    # the gDistance method
    starttime <- Sys.time()
    ## Set up container for results
    n <- length(ptsUTM)
    nearestCantons <- character(n)
    ## For each point, find name of nearest polygon (in this case, Belgian cantons)
    for (i in seq_along(nearestCantons)) {
        nearestCantons[i] <- pUTM$NAME_2[which.min(gDistance(ptsUTM[i,], pUTM, byid=TRUE))]
    }
    Sys.time()-starttime
    
    # the nn2 method
    starttime <- Sys.time()
    ## create search points and associate with polygon attributes
    rp <- spsample(pUTM,n=10000,type="regular")
    rp2 <- point.in.poly(rp,pUTM)
    # search for nearest point (with radius)
    nn <- nn2(coordinates(rp2),coordinates(ptsUTM),k=1,searchtype="radius",radius=5000)$nn.idx
    nearestCantons2 <- rp2$NAME_2[nn]
    Sys.time()-starttime
    
    

提交回复
热议问题