繁体   English   中英

如何将给定过程迭代 1'000 次并对结果进行平均

[英]How to iterate a given process 1'000 times and average the results

我来这里是想请教一下R语言,如何构造一个循环来迭代一些函数几次。

这是我的问题:我有一个从以前的分析 ( matrix1 ) 中获得的数字矩阵,我想将它与另一个数字矩阵进行比较(使用overlap function 产生单个值),我通过使用一组随机创建的点,与第一个数字矩阵中的值一样多。 我想重复随机抽样程序 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.

我希望我以清晰易懂的方式提出了我的问题,我希望你能帮助我解决这个问题。

提前谢谢大家,祝大家有个美好的一天!

我能想到的简单方法是使用“复制”:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM