Reputation: 43
I have 4 subfolder that contains 5 rasters with continuous values. So a build a loop with "for" function to :
My issue is in a step 4. Eventhough I use the argument "byLayer = T" in writeRaster function the rasters saved were a rasterstack with the 5 binary rasters. And i want write it per raster, per file, per band
I really grateful if anyone give me any insights
setwd("Vole_raw_mean_Present/")
sub <- list.dirs(full.names=FALSE, recursive=FALSE)
for(j in 1:length(sub)) {
print(sub[j])
h <- list.files(path=sub[j], recursive=TRUE, full.names=TRUE, pattern='.tif')
print(h)
stack_present <- stack(h)
print(stack_present)
binary_0.2 <- stack_present >=0.2
writeRaster(binary_0.2, filename=paste0(sub[j], bylayer = T, suffix = "_bin.tif"), overwrite=TRUE)
}
Upvotes: 0
Views: 282
Reputation: 47146
This is wrong because the argument "bylayer" is lost as it becomes part of the filename)
writeRaster(binary_0.2, filename=paste0(sub[j], bylayer = T, suffix = "_bin.tif"), overwrite=TRUE)
It should be something like this (and it helps to do it in two steps)
f <- paste0(sub[j], "bin.tif")
writeRaster(binary_0.2, filename=f, bylayer=TRUE, overwrite=TRUE)
Illustrated here
library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))
dir.create("test")
setwd("test")
writeRaster(b, filename="abc.tif", bylayer=T)
list.files()
#[1] "abc_1.tif" "abc_2.tif" "abc_3.tif"
writeRaster(b, filename="bin.tif", bylayer=T, suffix = paste0("f", 1:3))
list.files(pattern="bin")
#[1] "bin_f1.tif" "bin_f2.tif" "bin_f3.tif"
Alternatively, you can loop over the files within each folder
Upvotes: 1