I am trying to get R to read a folder containing raster files, and then in a foor loop, extract quantile values from each of the raster to enventually process each raster with a substraction involving the quantile. The final step is to create a mean raster with the processed rasters but I'm struggling.
Here is what I've been writing so far:
path <- "C:/fichierR/rastermasque"
files <- list.files(path, pattern = "tif$", full.names = TRUE)
for(f in files){
decile <- quantile(f, probs = c(0.10))
r3 <- r2-decile
r4 <- calc(r3, fun = mean)
writeRaster(r4, "C:/fichierR/mean.tif", overwrite = TRUE)
}
The script when not in a for loop runs correctly but there are multiple errors in my attempt.
1 Answer 1
I have posted a code that should work below. If there is an error just tell me and I will adapt it. In your code there are several false assumptions, that's why it is not working. Here is an explanation for the main errors:
decile <- quantile(f, probs = c(0.10))
your are trying to calculate deciles for a character. You first have to read in the raster with the path which is f in this case. For this raster you can then calculate the quantiles. Then you need to calculate the decile for all your rasters and then apply the mean function to it, what you are doing is just calculating the mean from one raster, which simply won't give any valuable result - you are only saving the last raster in your folder as mean raster.
Herer is the code that should work (assuming your extent etc. is the same for all your raster):
library(raster)
#get the path
path <- "C:/fichierR/rastermasque"
#list all files
files <- list.files(path, pattern = "tif$", full.names = TRUE)
#create an empty stack that will be filled one by one in the for-loop to then be able to calculate the mean from all the changed rasters
mean_stack <- stack()
for (f in files){
# load one raster
r <- raster(f)
# calculate the quantile for the raster
decile <- quantile(r, probs = c(0.10))
# substract the decile from the raster
diff <- r - decile
# add the raster to a stack
mean_stack <- stack(mean_stack,diff)
}
#calculate the mean of the raster stack
mean_calc <- calc(mean_stack, fun= mean)
writeRaster(mean_calc, "C:/fichierR/mean.tif", overwrite = T)
-
Thank you for your answer, I just tested the code you provided and it worked like a charm. thank you so much ! Indeed, I thought "f" was by default the files in the folder I specified.. !Perrin Remonté– Perrin Remonté2020年04月30日 10:58:59 +00:00Commented Apr 30, 2020 at 10:58