对于较大的.tif文件,.calcTest中出现R错误

wz1wpwve  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(132)

我有175个tif文件,包括整个地球仪(土地)的各种作物的网格数据。我想创建一个单一的光栅数据集,只包含最高值的索引。这样,对于每个单元格,我知道哪种作物具有最高值。
我的代码可以正常工作。但是如果我运行calc()函数,我有时会得到一个我无法解释的错误:
第一个月

  1. library(raster)
  2. # Get the file names for later import
  3. file_list <- list.files(path = "C:/folder/test", full.names = TRUE)
  4. filtered_file_list <- file_list[grep("HarvestedAreaFraction.tif",file_list,fixed=TRUE)]
  5. #init
  6. raster_stack <- stack()
  7. crop_names <- character() #list to save the index of crops
  8. for (file_path in filtered_file_list){
  9. raster_layer <- raster(file_path)
  10. # Aggregate the raster to a 1-degree resolution, all tif-files have the same resolution
  11. aggregated_raster_layer <- aggregate(raster_layer, fact=c(12,12), fun=mean)
  12. raster_layer <- na.omit(aggregated_raster_layer)
  13. raster_stack <- addLayer(raster_stack, raster_layer)
  14. crop_name <- gsub(".*/(.*?)_HarvestedAreaFraction\\.tif$", "\\1", file_path)
  15. crop_names <- c(crop_names, crop_name)
  16. }
  17. # Function to get the name of the crop with the maximum fraction
  18. get_max_crop_name <- function(x, na.rm = TRUE, ...) {
  19. max_index <- which.max(x)
  20. # max_name <- crop_names[max_index]
  21. if (length(max_index) == 0 || all(x == 0) || all(is.na(x))) {
  22. max_name <- 0
  23. } else {
  24. max_name <- max_index
  25. }
  26. return(max_name)
  27. }
  28. max_crop_raster <- calc(raster_stack, fun=get_max_crop_name, na.rm=TRUE)

字符串

只有当我导入较大的tif-files时才会出现此错误。在175个文件中,约有100个文件约为30 MB,其他文件约为2- 3 MB。对于较小的文件,它可以正常工作,但一旦我包含其中一个较大的文件,我就会出现此错误

有什么想法吗?

wz3gfoph

wz3gfoph1#

这不起作用的原因是你的函数没有 * 向量化 *,因为if语句一次只能计算一个值。
你不需要任何这些东西,因为你可以像这样使用wich.max .(用“terra”代替“raster”):

  1. library(terra)
  2. ff <- list.files(path = "C:/folder/test", full.names = TRUE, pattern="HarvestedAreaFraction.tif")
  3. x <- rast(ff)
  4. mxcrop <- which.max(x)

字符串

相关问题