```
library(raster)
N <- 2
dirRas <- raster(extent(0,40,0,40), res = 1)
coords <- cbind(x = round(runif(N, xmin(dirRas), xmax(dirRas)))+0.5,
y = round(runif(N, xmin(dirRas), xmax(dirRas)))+0.5,
id = 1:N)
dirs1 <- directionFromEachPoint(from = coords, landscape = dirRas)
require(CircStats)
dirs1[, "angles"] <- deg(dirs1[,"angles"] %% (2*pi))
indices <- cellFromXY(dirRas,dirs1[, c("x", "y")])
minDir <- tapply(dirs1[,"angles"], indices, function(x) min(x)) # minimum angle
dirRas[] <- as.vector(minDir)
if (interactive()) {
Plot(dirRas, new = TRUE)
library(sp)
start <- SpatialPoints(coords[, c("x", "y"), drop = FALSE])
Plot(start, addTo = "dirRas")
}
```

Run the code above in your browser using DataLab