Search code examples
rfor-loopraster

How do you load multiple rasters in [r] using a for loop?


I am trying to load 144 rasters (.tif) using a loop that refers to lists, but running into errors. Note that my directory only has these 144 .tif files in it, and there are portions of each filename that are unique. I'm not sure how to best create a minimally reproducible example for this, so I've abbreviated directories and file names.

first I loaded "raster" package and set my working directory, then I also set a variable 'path' equal to my working directory. Next, I created a list of the files in the directory

setwd("T:/sample/geotiffs")
path<-"T:/sample/geotiffs"
rastlist <- list.files(path=path, pattern='tif$', full.names=TRUE)

I tried to write my code with syntax from a previous post: File not found in R raster loop

for (jj in 1:length(mget(rastlist)))  {
  x[jj] <- raster(paste0(rastlist[jj]))
}

However, I got the following error about missing the first file: "Error: value for ‘T:/sample/geotiffs/geotiff1.tif’ not found"

I also tried coding it this way without the mget() and paste0(),

x<-vector(mode="logical",length=144)
for(i in 1:length(rastlist))  {
  x[i]<-raster(rastlist[i])
}

However, I am getting 50+ warnings "1: In x[i] <- raster(rastlist[i]) : number of items to replace is not a multiple of replacement length"

Any ideas? After I run this code my vector, x, seems to be a vector with 144 random integers and I am not sure why - perhaps I need a better way to initiate a blank vector 'x' with length equal to my rastlist?


Solution

  • This should work:

    library(raster)
    f <- list.files(path=path, pattern='tif$', full.names=TRUE)
    r <- lapply(f, raster)
    

    If the rasters have the same extent and resolution, you might want to do this instead

    s <- stack(f)