To calculate the proximity scores for each feature, you can use the gDistance function from the rgdal package.
First, you'll need to convert your spatial feature object to a SpatialPointsDataFrame or SpatialPolygonsDataFrame, depending on the type of features you have. Let's say you have a SpatialPolygonsDataFrame called buildings.
library(rgdal)
# Convert to SpatialPolygonsDataFrame if necessary
buildings.spdf <- SpatialPolygonsDataFrame(buildings, data = buildings@data)
Next, you'll create a function to calculate the proximity scores for each feature. This function will take the buildings.spdf object, the index of the feature you want to calculate the scores for, and the number of nearest neighbors you want to consider.
calculate.proximity <- function(spdf, feature.index, k = 10) {
# Extract the polygon and coordinates of the feature we want to calculate scores for
feature.polygon <- spdf@polygons[[feature.index]]
feature.coords <- spdf@polygons[[feature.index]]@coords
# Calculate the distances between this feature and all other features
distances <- spdf@proj4string(add = TRUE) %>%
gDistance(x = feature.coords, y = spdf@polygons, fun = "euclidean") %>%
as.data.frame() %>%
setNames(names(spdf@data))
# Sort the distances by distance and extract the k nearest neighbors
distances <- distances[order(distances[, 1]), ][1:k, ]
# Calculate the scores as the average distance to the nearest neighbors
scores <- apply(distances, 1, function(x) mean(x[, 1]))
# Add the scores to the original data frame for this feature
spdf@data[feature.index, "proximity"] <- scores
# Return the updated SpatialPolygonsDataFrame