I'm trying to calculate Topographic Position Index (TPI) for 177 points of interest. I have their coordinates stored in a data.frame and elevation in a raster of 7.5 arc sec spatial resolution. And the TPIs I'm calculating is basically: the elevation of point of interest minus the average elevation of its surrounding cells, then the intermediate result is divided by the spatial resolution of the raster. (resolution(dem))
to account for differences in the spatial scale of the DEM and the TPI values.
And since studies usually calculate two TPIs (a small scale + a large scale), I'm also using two windows, where in the small one the surrounding 55 cells are used, and in the large one the surrounding 1010 cells are used.
I am getting this error message
Error in .focal_fun(v, w, as.integer(c(tr$nrows[1] + addr, nc)), runfun, :
Evaluation error: could not find function "resolution"
Code:
library(raster)
library(sp)
library(terra)
library(haven)
# Make a dataframe with longitudes and latitudes
df <- data.frame(lon = coords$longitude, lat = coords$latitude)
# Convert the dataframe to a SpatialPointsDataFrame
coordinates(df) <- c("lon", "lat")
proj4string(df) <- CRS("+proj=longlat +datum=WGS84")
# Extract the elevation values at the points
elev <- extract(dem, df)
# Define the scales for TPI calculation
scales <- c(5, 10)
# Loop over the scales and calculate TPI
tpi_list <- list()
for (scale in scales) {
# Define the size of the moving window
win_size <- scale * 5
# Calculate TPI
tpi <- focal(dem, w = matrix(1, win_size, win_size), fun = function(x) {
(elev - mean(x)) / resolution(dem) * 5
})
# Extract TPI values at the points
tpi_vals <- extract(tpi, df)
# Store the TPI values in a list
tpi_list[[as.character(scale)]] <- tpi_vals
}
#Error in .focal_fun(v, w, as.integer(c(tr$nrows[1] + addr, nc)), runfun, : Evaluation error: could not find function "resolution"
# Combine the TPI values for different scales into a dataframe
tpi_df <- data.frame(tpi_list, row.names = rownames(df))