Finding euclidean distance in R{spatstat} between points, confined by an irregular polygon window

前端 未结 1 1631
北恋
北恋 2020-12-06 20:14

I\'m trying to find the euclidean distance between two points, confined by an irregular polygon. (ie. the distance would have to be calculated as a route through the window

相关标签:
1条回答
  • 2020-12-06 20:56

    OK, here's the gdistance-based approach I mentioned in comments yesterday. It's not perfect, since the segments of the paths it computes are all constrained to occur in one of 16 directions on a chessboard (king's moves plus knight's moves). That said, it gets within 2% of the correct values (always slightly overestimating) for each of the three pairwise distances in your example.

    library(maptools)  ## To convert spatstat objects to sp objects
    library(gdistance) ## Loads raster and provides cost-surface functions
    
    ## Convert *.ppp points to SpatialPoints object
    Pts <- as(test.ppp, "SpatialPoints")
    
    ## Convert the lake's boundary to a raster, with values of 1 for
    ## cells within the lake and values of 0 for cells on land
    Poly <- as(bound, "SpatialPolygons")           ## 1st to SpatialPolygons-object
    R <- raster(extent(Poly), nrow=100,  ncol=100) ## 2nd to RasterLayer ...
    RR <- rasterize(Poly, R)                       ## ...
    RR[is.na(RR)]<-0                               ## Set cells on land to "0"
    
    ## gdistance requires that you 1st prepare a sparse "transition matrix"
    ## whose values give the "conductance" of movement between pairs of
    ## adjacent and next-to-adjacent cells (when using directions=16)
    tr1 <- transition(RR, transitionFunction=mean, directions=16)
    tr1 <- geoCorrection(tr1,type="c")
    
    ## Compute a matrix of pairwise distances between points
    ## (These should be 5.00 and 3.605; all are within 2% of actual value).  
    costDistance(tr1, Pts)
    ##          1        2
    ## 2 3.650282         
    ## 3 5.005259 3.650282
    
    ## View the selected paths
    plot(RR)
    plot(Pts, pch=16, col="gold", cex=1.5, add=TRUE)
    SL12 <- shortestPath(tr1, Pts[1,], Pts[2,], output="SpatialLines")
    SL13 <- shortestPath(tr1, Pts[1,], Pts[3,], output="SpatialLines")
    SL23 <- shortestPath(tr1, Pts[2,], Pts[3,], output="SpatialLines")
    lapply(list(SL12, SL13, SL23), function(X) plot(X, col="red", add=TRUE, lwd=2))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题