我有175个tif文件,包括整个地球仪(土地)的各种作物的网格数据。我想创建一个单一的光栅数据集,只包含最高值的索引。这样,对于每个单元格,我知道哪种作物具有最高值。
我的代码可以正常工作。但是如果我运行calc()函数,我有时会得到一个我无法解释的错误:
第一个月
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-files时才会出现此错误。在175个文件中,约有100个文件约为30 MB,其他文件约为2- 3 MB。对于较小的文件,它可以正常工作,但一旦我包含其中一个较大的文件,我就会出现此错误
有什么想法吗?
1条答案
按热度按时间wz3gfoph1#
这不起作用的原因是你的函数没有 * 向量化 *,因为
if
语句一次只能计算一个值。你不需要任何这些东西,因为你可以像这样使用
wich.max
.(用“terra”代替“raster”):字符串