簡體   English   中英

使用R循環遍歷具有不同長度的柵格和數字列表

[英]Looping over a raster and numeric lists with different lengths using R

我有兩個列表對象。 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
  }
}

我設法找到了解決辦法。 我確信仍然有一種方法可以使用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)]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM