Search code examples
rgisrasterspatial

How to read multiple ".asc" raster files into R


I am trying to read multiple raster files into R so I can merge them into one, larger raster. Most of the files are ASCII files, though some are also TIF files.

I have tried the code from how to efficiently import multiple raster (.tif) files into R but always receive error messages. I don't think it's to do with my files as I can read in the individual rasters one at a time and merge them fine. I'm ultimately dealing with hundreds of rasters though so need a way to process them all at once!

My example data is within the folder "HowesValley", which is a subfolder within my working directory.

When I input:

rastlist <- list.files(path = "/HowesValley", pattern='.asc', all.files=TRUE, full.names=FALSE)
allrasters <- stack(rastlist)

I received the error

Error in x[[1]] : subscript out of bounds

I have also tried:

rastlist <- list.files(path = "/HowesValley", pattern='.asc', all.files=TRUE, full.names=FALSE)
allrasters <- lapply(rastlist, raster)

When I input

allrasters[[1]]

I get

Error in allrasters[[1]] : subscript out of bounds

And when I input

plot(allrasters[[1]])

I get

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'plot': subscript out of bounds

Any ideas?


Solution

  • Answering my own question as I found a method that works, in case anyone else runs into the same trouble!

    I found the code I needed from https://www.r-bloggers.com/2014/04/merge-asc-grids-with-r/ and How to select multiple files with different extension in filelist in R

    The code that works for me is:

    library(rgdal)  
    library(raster) 
    setwd("D:/HowesValley") #set the working directory to the folder of interest
    f <-list.files(path = ".",pattern = '.*\\.(tif|asc)$') #search for both .tif and .asc files
    r <- lapply(f, raster) 
    x <- do.call("merge",r) 
    plot(x)
    writeRaster(x,"HowesValleyComb.asc")