0
library(terra)

a=rast(nrows=10,ncols=10,vals=1:100)

b=rast(nrows=10,ncols=10,vals=1:100)

c=rast(nrows=10,ncols=10,vals=1:100)

test <- c(a,b,c)

for (i in 1:3) 
{
  r=test[[i]]
  writeRaster(r,paste0("E:/test",i,'.tif'))
}

This is my way to do it. I want to know is there a easier way to do it?

1 Answer 1

1

You can pass a vector of filenames to writeRaster directly to extract multiple layers:

library(terra)
#> terra 1.6.7

a <- rast(nrows=10, ncols=10, vals=1:100)

b <- rast(nrows=10, ncols=10, vals=1:100)

c <- rast(nrows=10, ncols=10, vals=1:100)

test <- c(a,b,c)

fnames <- paste0("test", 1:nlyr(test), ".tif")

writeRaster(test, fnames)

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.