0

I want to loop through two directories simultaneously. Both directories contain raster-images, one the initial images the other one the masks for these images.

I would like to access them outside the loops since I have to do some calculations but also keep my folder structures.

The loops don't have to be nested in each other, I guess, but how can I access the files outside the loop? Creating an empty stack/raster outside and fill it with the values from the stack/raster of the loops does not seem to the trick.

So far I got this:

library(raster)

files1 = list.files(path2, pattern = "*.tif", full.names = TRUE)
files2 = list.files(path4, pattern = "*_cmask.tif", full.names = TRUE)
f1Stack = stack()
for (f1 in files1) {
    f1Stack = stack(f1)
         do stuff with f1Stack
    for (f2 in files2) {
        f2Raster = raster(f2)
        do stuff with f2Raster
    }
 }

edit:
I want to store the Raster Stack created inside the loop to be accessible outside. files1 contains 10 multiband-tiffs. If I create an empty stack outside the loop try to update it with the current stack in the loop, it always contains just the last stack of the loop.

Aldi Kasse 2
  • 143
  • 1
  • 13
  • 1
    It would be helpful if you could be a bit more specific on what exactly you're trying to achieve (what do you want to do with the rasters?) and if possible add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Val Mar 19 '18 at 14:15

1 Answers1

1

You probably would want to start this way:

library(raster)
files1 <- list.files(path2, pattern = "\\.tif$", full.names = TRUE)
files2 <- list.files(path4, pattern = "_cmask\\.tif$", full.names = TRUE)
s1 <- lapply(files1, brick)
s2 <- lapply(files2, brick)

That is, create a list of RasterBrick objects (more efficient that RasterStack) of each file. Than you can manipulate each object in the list (loop or another lapply), and you won't loose them.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63