R语言 如何将给定的过程迭代1,000次并计算结果的平均值

f45qwnt8  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(130)

我在这里问你关于R语言的知识,以及如何构造一个循环来迭代一些函数几次。
我的问题是:我从之前的分析中得到了一个数值矩阵(matrix1)要比较的对象(使用overlap函数得到单个值)与另一个数值矩阵进行比较,该数值矩阵是通过使用一组随机创建的点提取给定栅格的值得到的,与第一个数值矩阵中的值一样多。我想重复随机采样过程1,000次,为了得到1,000个不同的随机点集合,然后用matrix1重复比较1,000次(每组随机点一次),最后,计算结果的平均值以得到单个值。
下面我给你一个我想使用的函数的例子:

#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.

我希望我的问题是清楚明白的,希望你能协助我解决这个问题。
提前感谢大家,祝大家有美好的一天!

py49o6xq

py49o6xq1#

我能想到的简单方法是使用“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)

相关问题