Reputation: 67
I have this rasterbrick/stack that I need to write individual files into a folder. I have done this task several times before but some of the recent improvements to terra
and raster
have rendered some of my codes unusable and I'm not sure where the problems are because the error messages are not intuitive.
Here's my code:
writeRaster(myraster, file.path("D:/...filepath/",
names(myraster)), bylayer=T, format='GTiff', overwrite = T)
Error in file(fn, "rb") : cannot open the connection In addition: Warning message: In file(fn, "rb") : cannot open file 'C:...\AppData\Local\Temp\RtmpEvVX4G\raster\r_tmp_2023-09-25_235519.636784_15272_51613.gri': No such file or directory
So following the error message, I went and deleted all the folders in my Temp
folder except those in use. The code then started to throw a totally different error message.
Error: [writeStart] cannot overwrite existing file
Here's the test data
Upvotes: 1
Views: 529
Reputation: 25
FWIW, I get the same error running the code snippet above copy and pasted directly. It works if I subset it to only one layer, e.g "writeRaster(b[[3]]...". But it throws the following if I try to do more than one.
"Error in .startGDALwriting(x, filename, gdal = options, ...) : formal argument "sources" matched by multiple actual arguments"
raster_3.6-20 sp_1.6-1
terra_1.7-29 ("loaded via a namespace (and not attached)")
R version 4.2.3
Note I work for a gov't agency and cannot install new R versions until they have been approved by our IT staff.
update... I ran this on my personal MacOS machine with R 4.3.2 and it worked fine, so probably a version issue. Maybe a Windows issue.
Falling back on a good old fashioned for loop.
for (i in seq(1:length(names(b)))) {
writeRaster(b[[i]], file.path("E:...", names(b[[i]])),format="GTiff", bylayer=T, overwrite=T)
}
Upvotes: 0
Reputation: 47536
This works for me:
library(raster)
dir.create("d:/...filepath", FALSE, FALSE)
b <- brick(nrow=5, ncol=5, nl=3)
values(b) <- 1:75
names(b) <- c("A", "B", "C")
x <- writeRaster(b, file.path("D:/...filepath/", names(b)),
format="GTiff", bylayer=T, overwrite=T)
x
#class : RasterStack
#dimensions : 5, 5, 25, 3 (nrow, ncol, ncell, nlayers)
#resolution : 72, 36 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#names : A, B, C
#min values : 1, 26, 51
#max values : 25, 50, 75
filename(x[[1]])
#[1] "D:\\...filepath\\A.tif"
Note that filetype
is an argument for terra::writeRaster
. But as you are using a RasterBrick, you are using raster::writeRaster
and there the equivalent argument is called format
. To avoid confusion you can leave the argument out and append ".tif" to filename instead.
Upvotes: 1