Search code examples
rlistloopsfor-loopraster

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


I have two list objects. Threshold_List is a list of values (type double) with length 2. Raster_List is a list of rasters with length 10. I am trying to loop over these two lists, but I am not sure how to do this.

For every element in Threshold_List, I want to reuse the same value up until a specific amount of times (reps), before continuing the loop on to the next value in Threshold_List.

In actuality, I want to use the first value in Threshold_List to mask the first 5 elements in Raster_List, and then move on to the second value in Threshold_List to mask the next 5 elements in Raster_List, and so on.

The following code works when the lists are of equal length. How can I change this to include some sort of repeats / reps?

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
  }
}

Solution

  • I managed to find a work around. I am sure there is still a way to rather use rep or repeat{}, so this is still open for anyone to answer.

    The working code is as follows. I just removed the rasters from the list after every loop.

    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)]
    }