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

问题描述 投票:0回答:1

我有 175 个 tif 文件,包括全球(陆地)各种作物的网格数据。我想创建一个仅包含最高值索引的栅格数据集。这样对于每个单元格,我都知道哪种作物具有最高的价值。

我的代码有效。但如果我运行 calc() 函数,有时会出现无法解释的错误:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :  cannot use this function. Perhaps add '...' or 'na.rm' to the function arguments?

library(raster)
# Get the file names for later import
file_list <- list.files(path = "C:/folder/test", full.names = TRUE)
filtered_file_list <- file_list[grep("HarvestedAreaFraction.tif",file_list,fixed=TRUE)]

#init
raster_stack <- stack()
crop_names <- character() #list to save the index of crops


for (file_path in filtered_file_list){
  raster_layer <- raster(file_path)
  
  # Aggregate the raster to a 1-degree resolution, all tif-files have the same resolution
  aggregated_raster_layer <- aggregate(raster_layer, fact=c(12,12), fun=mean) 
  raster_layer <- na.omit(aggregated_raster_layer)
  
  raster_stack <- addLayer(raster_stack, raster_layer)
  crop_name <- gsub(".*/(.*?)_HarvestedAreaFraction\\.tif$", "\\1", file_path)
  crop_names <- c(crop_names, crop_name)
}

# Function to get the name of the crop with the maximum fraction
get_max_crop_name <- function(x, na.rm = TRUE, ...) {
  max_index <- which.max(x)
#  max_name <- crop_names[max_index]
  if (length(max_index) == 0 || all(x == 0) || all(is.na(x))) {
    max_name <- 0
  } else {
    max_name <- max_index
  }
  return(max_name)
}

max_crop_raster <- calc(raster_stack, fun=get_max_crop_name, na.rm=TRUE)

仅当我导入较大的 tif 文件时才会出现该错误。在 175 个文件中,大约有 100 个文件大小约为 30MB,其他文件大小约为 2-3MB。它对于较小的文件工作得很好,但是一旦我包含其中一个较大的文件,我就会收到此错误

有什么想法吗?

r raster tiff r-raster grib
1个回答
0
投票

这不起作用的原因是你的函数不是向量化,因为

if
语句一次只能计算一个值。
无论如何,您不需要任何这些,因为您可以使用
wich.max
。像这样(用“terra”代替“raster”):

library(terra)
ff <- list.files(path = "C:/folder/test", full.names = TRUE, pattern="HarvestedAreaFraction.tif")

x <- rast(ff)
mxcrop <- which.max(x)
© www.soinside.com 2019 - 2024. All rights reserved.