I am trying to calculate the distance from a spatial point to a raster cell of a particular value/type. In my data each point represents a tree and I want to know how far away that point is from different categories of raster cells (grass, forest, impervious surface etc). I tried distanceFromPoints but that returns a distance raster and what I'm interested in is a data frame with distances to the nearest raster cell of each land cover type from each point.
#example raster
library(raster)
r <- raster(nrow=100, ncol=100)
r[] <- round(runif(ncell(r),1,4),0)
plot(r)
#example points
x <- c(-110, -50, 25, 150)
y <- c(50, -25, 70, 2)
df <- data.frame(cbind(x,y))
df$n <- c("pt1","pt2","pt3","pt4")
library(sp)
sp <- SpatialPoints(c, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs"))
plot(sp, add=TRUE)
The output I want is something like this:
x y n dist.cat1 dist.cat2 dist.cat3 dist.cat4
1 -110 50 pt1 12 3 5 9
2 -50 -25 pt2 1 2 1 27
3 25 70 pt3 4 14 29 5
4 150 2 pt4 23 2 15 2
Where dist.cat1 represents the distance from a point (n) to the nearest raster cell that has the category 1 value.