# Euclidean distance raster

1 message
Open this post in threaded view
|

## Euclidean distance raster

 Hi all, I want to create a nearest distance raster in R. As far as I know, the common practice is to compute the distance matrix of all the points in the mask raster to all the features in the vector layer, then calculate the min distance for each point. But this makes a huge (m by n) matrix and it involves a lot of computation which is too slow. To go around the computation, I wrote the following function that first gets the index of the nearest feature to each point in the mask raster, then only calculates the distance between each point and its nearest feature. This solution is 3 times faster than the previous one, but still not fast enough. I wonder if anyone knows a better solution to this problem. Thank you in advance, Roozbeh Valavi rasterDistance <- function(feature, rastermask){   require(raster)   require(sf)   require(progress)   p <- st_as_sf(rasterToPoints(rastermask, spatial = TRUE))   p\$indx <- st_nearest_feature(st_geometry(p), st_geometry(feature))   pb <- progress::progress_bar\$new(format = " Progress [:bar] :percent in :elapsed",                                    total=nrow(p), clear=FALSE, width=75) # add progress bar   for(i in 1:nrow(p)){     p\$dist[i] <- st_distance(st_geometry(p[i,]), st_geometry(feature[p\$indx[i],]))     pb\$tick() # update progress bar   }   output <- raster::rasterize(p, rastermask, field = "dist")   return(output) } -- *Roozbeh Valavi* PhD Candidate The Quantitative & Applied Ecology Group School of BioSciences | Faculty of Science The University of Melbourne, VIC 3010, Australia Mobile: +61 423 283 238         [[alternative HTML version deleted]] _______________________________________________ R-sig-Geo mailing list [hidden email] https://stat.ethz.ch/mailman/listinfo/r-sig-geo