for loop to permute random centroids and calculate their distance from nearest features

Hi, I have shape layers with four features (e.g. lakes, peatlands, burned, and forests). I want to know if forest patches are located by chance or related to wet features. I want to calculate the nearest distance of forest centroids to wet features (lake and peatland) then I must do a permutation for 1000 random points picked in burned and forest features and compare the nearest distance of forest centroids with the nearest distance of random points.
This is the code I used:
tt_list <- list.files(path = "/Volumes/NO NAME/QGIS/NewSpatialAnalysis/FR",
pattern = ".gpkg",
full.names = T,
recursive = T)
allmaps_shape <- lapply(tt_list, st_read)
#to combine two wet features (i.e water and peatland)
wet <- allmaps_shape[[1]] %>%
dplyr::filter(DN !=5) %>%
dplyr::filter(DN !=4)

to combine burned and forest features as an input for permuting random points

rest <- allmaps_shape[[1]] %>%
dplyr::filter(DN!=1) %>%

forest <- allmaps_shape[[1]] %>%
dplyr::filter(DN ==5)
centerfor <- st_centroid(forest) #to get forest centrooids
(nearest <- st_nearest_feature(centerfor, wet))
(dist <- st_distance(centerfor, wet[nearest,], by_element = TRUE))

Permutation of random forest centroids for one cell

n <- 999L
I.n <- vector(length = n)
for (i in seq_along(I.n)) {
randx <- sf::st_sample(rest, size = length(forest$DN), replace=FALSE)
nearestdis <- st_nearest_feature(randx, wet)
distrand <- st_distance(randx, wet[nearestdis, ], by_element = TRUE)
I.n[i] <- mean(distrand)

hist(I.n, main=NULL, xlab="Distance from wet features based on 999 permutations", xlim=c(15, 35))
abline(v=mean(dist), col="red")

As I have about 200 shape files, I'd like to automate R analysis as much as possible. I used list.files and lapply to read all files together but I can not successfully apply the for loop on the list files.

any help and guidance you can provide would be greatly appreciated.

Sample shape files could be found in this repository:

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.