0
votes

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?

2
How about foo <- lapply(rastlist, raster)?Lyngbakr
I think the error might be caused by the fact that you cannot save raster objects in a vector (I think it has to do with the fact that rasters are S4 objects); however, you can do it in a list. @Lyngbakr code should workJonathan V. Solórzano

2 Answers

3
votes

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)
0
votes

Have you tried:

x <- purrr:map(rastlist, raster)