How to write raster bylayer using terra package in R?

Viewed 647

I want to write rasters by layer using terra package. I am using the following code

library(terra)

# first create a raster
r1 <- r2 <- r3 <- rast(nrow=10, ncol=10)
# Assign random cell values
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
values(r3) <- runif(ncell(r3))
s <- c(r1, r2, r3)
s
plot(s)

writeRaster(s, names(s), overwrite=TRUE)

It gives me following error

Error: [writeRaster] cannot open file: C:/Users/nn/Desktop/lyr.1 In addition: Warning message: C:/Users/nn/Desktop/lyr.1: No such file or directory (GDAL error 4)

I want to have the same output available in raster package using the following function

raster::writeRaster(s, names(s), bylayer=TRUE, format='GTiff', overwrite=TRUE)
1 Answers

You have to do a little more work

dir.create("test")
setwd("test")
f <- paste0("test", 1:nlyr(s), ".tif")
r <- writeRaster(s, f, overwrite=TRUE)
list.files()
# [1] "test1.tif" "test2.tif" "test3.tif"

r
#class       : SpatRaster 
#dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#resolution  : 36, 18  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#sources     : test1.tif  
#              test2.tif  
#              test3.tif  
#names       :      lyr.1,      lyr.1,      lyr.1 
#min values  : 0.02075680, 0.01058152, 0.02179740 
#max values  :  0.9874134,  0.9990475,  0.9883418 

This also works:

names(s) <- c("a", "b", "c")
x <- writeRaster(s, names(s), overwrite=TRUE, filetype="GTiff")

But note the filenames do not get the tif extension

sources(x)
#    source nlyr
#1 ./test/a    1
#2 ./test/b    1
#3 ./test/c    1

So I would do

z <- writeRaster(s, paste0(names(s), ".tif"), overwrite=TRUE)

#class       : SpatRaster 
#dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#resolution  : 36, 18  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#sources     : a.tif  
#              b.tif  
#              c.tif  
#names       :          a,          b,          c 
#min values  : 0.02075680, 0.01058152, 0.02179740 
#max values  :  0.9874134,  0.9990475,  0.9883418 

The error messages have now been improved (see this issue)

Related