Search code examples
rfunctionraster

Raster calc function - issue with NA data


I am trying to apply a relatively simple 'raster math' computation between two rasters. I can't seem to figure out how to set NA values properly in my function. I've looked everywhere for an answer and tried a few different ways to solve this but to no avail.

library(raster)

#Edited with feedback
fun.calc <- function(x, y, ...)
{
tree.w <- sum(x / (100 - y), ...)
ifelse(is.na(x) | is.na(y), NA, tree.w)
}

r1 <- raster(nrow=50, ncol = 50)
r1[] <- 90
r1[4:10,] <- NA
r2 <- raster(nrow=50, ncol = 50)
r2[] <- 40
r2[9:15,] <- NA

#Try UPDATED
fun.calc(r1[,,1], r2[,,1], fun=fun.calc, na.rm=TRUE)

This doesn't thrown an error, but I do not get the correct values, which should be 1.5 everywhere that there are no NA values (I get 2850). I don't understand why this is doing this, but I imagine it has something to do with the vectors in the raster.

Thanks for your thoughts!


Solution

  • It seems like I had to do this to get a solution to this answer. I don't really understand why except for that this seems to work. If anyone has a better answer, that would be great.

    fun.calc1 <- function(x, y, ...)
    {
    tree.w <- sum(x / (100 - y), ...)
    length.xy <- length(which(!is.na(x) & !is.na(y)))
    ifelse(is.na(x) | is.na(y), NA, tree.w/length.xy)
    }
    
    fun.calc1(r1[1:length(r1)],r2[1:length(r2)], na.rm=T)
    

    Again, not sure why it works but I do get the correct answer of 1.5.