Ilan MS
Ilan MS

Reputation: 3

Efficient way to save multiple rasters within a single .pdf using R

I'm very new to R and am wondering if there's a faster way to save multiple rasters within a single .pdf than by manually entering each raster file name as I've done below:

pdf(file = "file_name.pdf", width = 11, height = 8.5)
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2004_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2005_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2006_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2007_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2008_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2009_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2010_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2011_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2012_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2013_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003-2013_trend.tif")))
dev.off()

Thank you in advance for your help!

Upvotes: 0

Views: 395

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47016

Start with a vector of filenames, that you can get with list.files. Perhaps like this

f <- list.files(dir_path_data, pattern="^nutrient_pollution.*\\.tif$", full=TRUE)

You can now make a list using lapply

library(raster)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
lapply(f, function(n) plot(raster(n)))
dev.off()

Or use a loop

pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (n in f) {
   r <- raster(n)
   plot(r)
}
dev.off()

If the rasters have the same extent and resolution, you can also do

s <- stack(f)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (i in 1:nlayers(s)) {  
   plot(s[[i]])
}
dev.off()

Upvotes: 2

Related Questions