Search code examples
rfor-loopgeospatiallapplyraster

lapply creates endless loop when attempting to stack rasters


I am attempting to produce a single raster image composed of other stacked raster images from my directory:

ncfiles <- list.files("~/Desktop/Summer 2020/Tropomi/Aerosol Height", full.names = T, pattern = "*.nc")

When I follow this example, and run this loop:

bigstack <- stack()

test <- function(file) { for (i in 1: length(ncfiles)){
  GetMyImage <- tryCatch(        
    {
      fname <-(ncfiles[i])
      f <- nc_open(fname)
      print(fname)
    },
    error=function(e) {
      message('Caught Error')
      print(e)
    },
    warning=function(w) {
      message('Caught Warning')
      print(w)
    },
    finally = {
      message('All done')
    }
  )
  if(inherits(errorCondition("ERROR :", next)))
  {
    varx <- attributes(f$var) $names
    vary <- ncvar_get(f, varx)
    rm(f)
    proj <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
    rbrick <- brick(vary, crs=proj)
    rm(vary)
    extent(rbrick) <- c(-180, -140, 10, 30)
    return(rbrick)
  }}}

Then attempt to stack:

allyrs <- lapply(ncfiles, test)

My loop runs on repeat, nonstop. What is causing my loop to run endlessly? And how may I produce the desired stacked raster image? Thanks for any input!


Solution

  • My problem here was making the loop too complicated and containing counter intuitive components like what was previously suggested in the comments. I reformatted the loop to:

    
    ncfiles <- list.files("~/Desktop/Summer 2020/Tropomi/Aerosol Height", full.names = T, pattern = "*.nc")
    
    bigstack <- stack()
    
    for (i in 1: length(ncfiles)){
          fname <-(ncfiles[i])
          f <- nc_open(fname)
      ah <- ncvar_get(f, varid = "DETAILED_RESULTS/aerosol_optical_thickness")
      lon <- ncvar_get(nc, varid = "PRODUCT/longitude")
      lat <- ncvar_get(nc, varid = "PRODUCT/latitude")
      nc_close(f)
       s1 <- data.frame(as.vector(lon), as.vector(lat), as.vector(ah))
       crsLatLon <- "+proj=longlat +datum=WGS84"
       ex <- extent(c(-180,180,-90,90))
       pmraster <- raster(ncol=360*10, nrow=180*10, crs=crsLatLon,ext=ex)
       pmraster <- rasterize(s1[,1:2], pmraster, s1[,3], fun=mean, na.rm=T)
       exHI <- extent(c(-180,-140,10,30))
       levelplot(crop(pmraster,exHI))
       bigstack <- stack(bigstack, pmraster)
       print("test")
    }
    
    stacking <- calc(bigstack, fun=mean, na.rm=T)
    levelplot(crop(stacking, exHI))