【发布时间】:2022-07-21 20:17:53
【问题描述】:
我有两个列表对象。 Threshold_List 是长度为 2 的值列表(双精度类型)。Raster_List 是长度为 10 的栅格列表。我正在尝试遍历这两个列表,但我不知道该怎么做。
对于Threshold_List 中的每个元素,我想重复使用相同的值直到特定次数(reps),然后继续循环到Threshold_List 中的下一个值。
实际上,我想使用Threshold_List 中的第一个值来屏蔽Raster_List 中的前5 个元素,然后继续使用Threshold_List 中的第二个值来屏蔽Raster_List 中的下5 个元素,等等。
以下代码在列表长度相等时有效。如何更改它以包含某种重复/代表?
library(raster)
# Create random list of rasters
r1 <- raster(nrows=10,ncols=10,res = 10, xmn = -100, xmx = 100, ymn = -100, ymx = 100)
Raster_List <- lapply(1:10, function(i) setValues(r1,runif(ncell(r1))))
Raster_names<-c("a","b","c","d","e","f","g","h","i","j")
names(Raster_List)<-Raster_names
rm(r1)
# Create list of values
#Threshold_List<-as.data.frame(rbind(0.2,0.2,0.2,0.2,0.2,0.9,0.9,0.9,0.9,0.9))
Threshold_List<-as.data.frame(rbind(0.2,0.9))
Threshold_List<-as.list(as.data.frame(t(Threshold_List)))
# This code works if both Threshold_List and Raster_List have equal length
i=1
for(tif in Raster_List) {
for(thresh in Threshold_List) {
name<-Raster_names[[i]]
# Assign crs
crs(tif)<-"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
# Mask based on threshold
tif[tif<thresh]<-NA
# Save output
tif_file<-paste0("Binary_",name)
writeRaster(tif,tif_file,format="GTiff",overwrite=TRUE)
i=i+1
}
}
【问题讨论】:
标签: r list loops for-loop raster