4

I am working with raster data (.tif) in R using the Raster Package, and I know how to create a raster object through

r <- raster(filename)

I am working with models with some long filenames, and so having to type out the filename is slowing me down. e.g.

filename <- "wc2.1_2.5m_bioc_CNRM-CM6-1_ssp245_2041-2060.tif"

Is there a way to create a raster object using my windows browser, or a simpler way to create raster objects, when I have multiple filenames with unwieldy names?

5

Function list.files() from base R allows to list files that match a pattern, in your case it would be .tif, or, if you only want those that start with wc it would be wc.*tif, using regular expressions. The argument full.names = T will give you complete names with directories, which helps to call these file names in functions; recursive = T tells the function to search in sub-directories

file_list = list.files(pattern = ".tif", full.names = T, recursive = T)

then you may read and stack the files using a for loop, such as:

library(raster)

raster::stack(file_list)
3
  • 6
    You do not need a loop to create a stack, you can just pass the vector eg., stack(list.files(pattern = ".tif", full.names = TRUE, recursive = TRUE)) Aug 10 '20 at 16:14
  • that package is always impressive
    – Elio Diaz
    Aug 10 '20 at 16:17
  • Thanks to both Elio and Diaz, this is precisely the kind of thing I'm looking for. It'll take me a little bit of practice, but this is great! Aug 10 '20 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.