2

This seems like A simple question but I'm not sure how to phrase it or ask. I want to bring in to r many rasters from many years and instead of typing them all out, I want to be able to define the year and bring in rasters by incorporating that defined year. This way I can copy and paste my code and instead of changing the year in every raster name, I can just change it once where I define the year.

Here is an example. I defined year as 2012 and in r.12 I tried using it to bring in the raster but this didn't work. r.1 is an example of how the rasters are all named.

year <- "2012"

r.12 <- raster("pr_total_mm_CRU_TS40_historical_12_"+year+".tif")
r.1 <- raster("pr_total_mm_CRU_TS40_historical_01_2012.tif")

2 Answers 2

3

You could try grep and list.files something along the lines of

rlist <- list.files(getwd(), "tif$")
r <- raster::stack(rlist[grep("2012", rlist)])
2

To concatenate text to produce the right filename, use the paste0() function:

year <- "2012"
fn <- paste0("pr_total_mm_CRU_TS40_historical_12_", year, ".tif")

r.12 <- raster(fn)

If you have a set of years and months to load, you might want a RasterStack, which could be built:

years <- 2010:2012
months <- 1:12
ym <- expand.grid(months = months, years = years)
ym <- paste(ym$months, ym$years, sep = "_")

rs <- stack(paste0("pr_total_mm_CRU_TS40_historical_", ym, ".tif")

You can refer to each layer (raster) like a list element, e.g. rs[[2]]

1
  • Working with lists of files as @Jeffrey mentions is a more reliable method, since minor changes in naming in a new dataset won't trip you up as much.
    – Simbamangu
    Commented Sep 10, 2020 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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