Reed
Reed

Reputation: 308

Using a for loop to write in multiple .grd files

I am working with very large data layers for a SDM class and because of this I ended up breaking some of my layers into a bunch of blocks to avoid memory restraint. These blocks were written out as .grd files, and now I need to get them read back into R and merged together. I am extremely new to R an programming in general so any help would be appreciated. What I have been trying so far looks like this:

merge.coarse=raster("coarseBlock1.grd")
for ("" in 2:nBlocks){
  merge.coarse=merge(merge.coarse,raster(paste("coarseBlock", ".grd", sep="")))
}

where my files are in coarseBlock.grd and are sequentially numbered from 1 to nBlocks (259)

Any feed back would be greatly appreciated.

Upvotes: 0

Views: 643

Answers (2)

Christopher Louden
Christopher Louden

Reputation: 7592

Using for loops is generally slow in R. Also, using functions like merge and rbind in a for loop eat up a lot of memory because of the way R passes values to these functions.

A more efficient way to do this task would be to call lapply (see this tutorial on apply functions for details) to load the files into R. This will result in a list which can then be collapsed using the rbind function:

rasters <- lapply(list.files(GRDFolder), FUN = raster)
merge.coarse <- do.call(rbind, rasters)

Upvotes: 1

Nathan Calverley
Nathan Calverley

Reputation: 1029

I'm not too familiar with .grd files, but this overall process should at least get you going in the right direction. Assuming all your .grd files (1 through 259) are stored in the same folder (which I will refer to as GRDFolder), then you can try this:

merge.coarse <- raster("coarseBlock1.grd")
for(filename in list.files(GRDFolder))
{
  temp <- raster(filename)
  merge.coarse <- rbind(merge.coarse, temp)
}

Upvotes: 0

Related Questions