Home > Enterprise >  How to iterate a given process 1'000 times and average the results
How to iterate a given process 1'000 times and average the results

Time:02-02

I am here to ask you about R language and how to construct a loop to iterate some functions several times.

Here is my problem: I have a numeric matrix obtained from previous analyses (matrix1) that I want to compare (using the overlap function that results in a single value) with another numeric matrix that I get by extracting values of a given raster with a set of randomly created points, as many as the values in the first numeric matrix. I want to repeat the random sampling procedure 1'000 times, in order to get 1'000 different sets of random points, then repeat the comparison with matrix1 1'000 times (one for each set of random points), and, in the end, calculate the mean of the results to get a single value.

Hereafter I give you an example of the functions I want to use:

#matrix1 is the first matrix, obtained before starting the potential loop;
#LineVector is a polyline shapefile that has to be used within the loop and downloaded before it;
#Raster is a raster from which I should extract values at points location;

#The loop should start from here:
Random_points <- st_sample(LineVector, size =  2000, exact = TRUE, type = "random")

Random_points <- Random_points[!st_is_empty(Random_points)]

Random_points_vect <- vect(Random_points)

Random_values <- terra::extract(Raster, Random_points_vect, ID = F, raw = T)

Random_values <- na.omit(Random_values[, c("Capriolo")]) 

Values_list <- list(matrix1, Random_values)

Overlapping_value <- overlap(Values_list, type = "2")

#This value, obtained 1'000 times, has then to be averaged into a single number.

I hope I have posed my question in a clear and understandable manner, and I hope you can help me with this problem.

Thanks to everyone in advance, I wish you a good day!

CodePudding user response:

Easy way i can figure out is to use "replicate":

values <- replicate(1000, {
  Random_points <- st_sample(LineVector, size =  2000, exact = TRUE, type = "random")
  Random_points <- Random_points[!st_is_empty(Random_points)]
  Random_points_vect <- vect(Random_points)
  Random_values <- terra::extract(Raster, Random_points_vect, ID = F, raw = T)
  Random_values <- na.omit(Random_values[, c("Capriolo")]) 
  Values_list <- list(matrix1, Random_values)
  Overlapping_value <- overlap(Values_list, type = "2")
  Overlapping_value
})

mean(values)
  • Related