【问题标题】:Looping over a raster and numeric lists with different lengths using R使用R循环遍历具有不同长度的栅格和数字列表
【发布时间】: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


    【解决方案1】:

    我设法找到了解决办法。我相信还有一种方法可以使用reprepeat{},所以这仍然是开放给任何人回答的。

    工作代码如下。我只是在每次循环后从列表中删除了栅格。

    i=1
    for(thresh in Threshold_List) {
    
      # Select the first 5 raster elements
      new_list_tif<-Raster_List
      new_list_tif<-new_list_tif[c(1:5)]
      
      # Loop over reduced list
      for(tif in new_list_tif) {
        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
      }
    
     # Removed processed rasters from list
     Raster_List<-Raster_List[-c(1:5)]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-23
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2017-12-14
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多