I have 3 rasters and I want to use them in a expression, but I can find different na values in the 3 rasters. For example: I can have a value in 2 rasters but in the 3 i have na,then in this case I cannot apply my expression.
Follow my code:
for(i in 1:length(name_BSA)){
i <- 1
if(days_BSA[i] == days_WSA[i] & days_WSA[i] == days_FDS[i]){
BSA <- raster(list_BSA[i])
WSA <- raster(list_WSA[i])
FDS <- raster(list_FDS[i])
brick <- brick(BSA, WSA, FDS)
if(!is.na(BSA[,]) & !is.na(WSA[,]) & !is.na(FDS[,])){
BLSA <- ((1-FDS[i])*BSA[i]) + (FDS[i] * WSA[i])
}
name_BLSA <- paste0("BLSA_",days_BSA[i])
writeRaster(BLSA, file.path(main,output_folder, name_BLSA), format = "GTiff", overwrite = T)
}
}
My problem is this part:!is.na(BSA[,]) & !is.na(WSA[,]) & !is.na(FDS[,])
This part does not work.
Someone can help me?
It would be easier to help if you supplied some code-generated example data, and omitted irrelevant detail such as the for-loop and if-clause.
For as far as I can see, there is no need to use !is.na
. If one of the values is NA
, the result will also be NA
. I assume that is what you want, although you do not have an else
clause. You should not use indexing on the RasterLayers with arithmetic operations. You also create a RasterBrick without using it.
library(raster)
# example data
output_folder = "."
f <- system.file("external/rlogo.grd", package="raster")
BSA <- raster(f, 1)
WSA <- raster(f, 2)
FDS <- raster(f, 3)
# improved code
BLSA <- (1-FDS)*BSA + FDS * WSA
name_BLSA <- file.path(output_folder, paste0("BLSA_", ".tif"))
writeRaster(BLSA, name_BLSA, overwrite = TRUE)
Alternatively, you could do
BLSA <- overlay(FDS, BSA, WSA, fun=function(x,y,z) { (1-x)*y + x*z }, filename=name_BLSA )