简体   繁体   中英

How to calculate distance from points to multipolygons within a buffer distance in R

I have a file with 52,000 points distributed in Brazil and a map of forest remnants (in polygon format).

What I want to do is calculate the distance from each point to each forest fragment that is within a buffer of, for example, 500m. So, if I have 3 fragments within a buffer of 500m, I want to have all three distances (euclidian) calculated from the centroid (focal point) to these fragments.

At the end I would like to take the mean distance from each focal point to their respective fragments.

I tried the function gWithinDistance,from the package "rgeos", like below:

near_frag_500 <- gWithinDistance (points, veg_natural, 500, byid=T)

being the argument "points" my focal points and "veg_natural" my forest remnant polygons. The number 500 refers to the buffer of 500m I want to calculate the distance. However, the output of this function is a matrix with TRUE or FALSE values. TRUE for those polygons which fall within the 500m buffer and FALSE for those polygons which fall outside the 500m buffer. It doesn´t give me the actual values of the distances calculated. I guess what I am looking for is an equivalent to the "Generate Near Table" function in ArcGIS.

I would really appreciate if someone could help me with that! I also have my forest remnants polygons in raster if there is any solution for that using a raster file.

I have made a simple test set with 7 points and 8 polygons. Everything has to be projected to a cartesian system in metres, so not lat-long. Use a local UTM zone if nothing else.

I compute the distance matrix from points to polygons:

> dmat = gDistance(points, veg_natural,byid=TRUE)

Then mask out anything over 500, and compute the row means:

> dmat[dmat>500]=NA
> apply(dmat, 1, mean, na.rm=TRUE)
       0        1        2        3        4        5        6        7 
331.5823 262.7129 380.2073 187.2068 111.9961      NaN 224.6962 360.7995 

and that is the mean of the distances from each point to the nearest features within 500m. Note the NaN for point 5 which is because it is not 500m from any polygon features.

If this matrix is too big for your case with 52,000 points (and ?? polygons?) then just do it for 1000 points at a time in a loop or whatever your computer can cope with. I think mine would fall over with 52,000.

If you want to know which of the polygons are the ones within 500m of each point, then something like:

> apply(dmat,1, function(r){which(!is.na(r))})
$`0`
5 6 
5 6 

$`1`
4 5 7 
4 5 7 

shows my first point (labelled 0) is near to polygons 5 and 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM