I have a raster representing a large landscape, where pixel values indicate particular land classes. I have been using the "distance" function in Package 'raster' in R to calculate the distance from all NA pixels to the nearest pixel with a value. In addition to the distance, I'm interested in knowing what the value was associated with the distance calculation. For example, if I have two land class values, e.g. 1= "Urban" and 2= "Agriculture", I'd like to know if a pixel is closest to an "Urban" pixel or an "Agriculture" pixel. I looked into the source code for the distance function, which converts the pixels to points and then calculates all relative distances but only returns the shortest distance. See below for an example of the distance function:
library(raster)
r <- raster(ncol=36,nrow=18)
r[] <- NA
r[500] <- 1
r[100] <-2
dist <- distance(r) #calculates the distance to the nearest non-NA pixel
Is there a function in a different package that does this (I'd like to stay in the R environment)?