Skip to content

Raster overlay / calc function with NA values

2 messages · Katrina Bennett, Lyndon Estes

#
Hi Katrina,

I might have misunderstood what you are trying to do, but its seems
the main problem is that you are using the calc function rather than
overlay. Also, I think you don't need the separate function for what
you are trying to achieve, if you are just trying to apply this to two
rasters:

# function not necessary, in the form I have written here, this would
produce the same results as your
# versions because sum() returns NA if you don't specify
# na.rm = TRUE
fun.calc <- function(x) {
 tree.w <- sum(x[[1]] / (100 - x[[2]]))  # but summing is superfluous
here in any case
 return(tree.w)
}

# So, based on the example, I think this achieves what you want to do.

r1 <- raster(nrow=50, ncol = 50)
r1[] <- sample(80:100, size=ncell(r1), replace = TRUE)  # added in
some variation here
r1[4:10,] <- NA
r2 <- raster(nrow=50, ncol = 50)
r2[] <- 40
r2[9:15,] <- NA

r3 <- r1 / (100 - r2)  # simple raster calculation
plot(r3)

# If you did want to use the function, you could do this.
st <- stack(r1, r2)
r4 <- calc(st, fun.calc)

plot(r3 - r4)

Is this what you were trying to do, or do you want to do a calculation
over more rasters?

Best, Lyndon
On Sun, May 25, 2014 at 4:19 PM, Katrina Bennett <kebennett at alaska.edu> wrote: