2

I have a large number of rasters (ASCII files) which I want to: 1. Reproject from Lamberts Equal area to WGS 84 2. Crop the resultant WGS 84 rasters to an extent 3. Write the resultant rasters to a directory

I know that stacking the rasters and reprojecting will run into memory problems. Therefore I tried a for loop which loops through each raster, reprojects crops and saves it to the output directory. Even then I run into memory problems. The code works quite fast if I just crop and mask the rasters, things get problematic when I wanna reproject. here is my code

library(raster)
library(doParallel)
library(rgdal)

#Define how many cores you want to use
UseCores <- detectCores()-1

#Register CoreCluster
cl       <- makeCluster (UseCores)
registerDoParallel (cl)

# Start the clock!
ptm <- proc.time ()

# Reading the shapefile (mask to crop later)
Maskshp  <- readOGR("G:/PhD BOKU/DATA/GIS Data/austria","AUT0")

# Name the output path and creat a directory to store the final results
outpath <- "C:/Users/chakraborty/Desktop/cropdata/"
dir.create(outpath)


# Reading the raster to crop
setwd("C:/Users/chakraborty/Desktop/MPI_rcp85_2080s_Bioclimatic")

files <- list.files(pattern=".tif") 

# add the output directory
outfiles <- paste0(outpath, files)

for(i in 1:length(files)) {
    r <-raster(files[i])
    projection(r)<- CRS("+proj=aea +lat_1=43 +lat_2=62 +lat_0=30 +lon_0=15 +x_0=0 +y_0=0 +ellps=intl 
    +units=m +no_defs")
    newproj <- CRS("+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
    rWGS <-  projectRaster(r, crs= newproj,res= 0.008333334)
    rc <- crop(rWGS, Maskshp)
    rc1 <- mask(rc,Maskshp)
    rc1 <- writeRaster(rc1, outfiles[i],format="GTiff")
}

#end cluster
stopCluster (cl)

# Stop the clock
proc.time() -ptm

# Takes 102 seconds to crop and write 20 rasters from Europe to Austrian Extent

0 Answers0