I am trying to run a function over two rasters. I am not sure what I'm
doing incorrectly, but I can not seem to get the answer I'm looking for,
even though the vectorized form of this function works well. I posted this
question on Stack Overflow but I think this is a raster issue... hence I
thought I might try this forum instead (
http://stackoverflow.com/questions/23852409/raster-calc-function-issue-with-na-data/23852610?noredirect=1#23852610
).


library(raster)

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

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)
}

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

#This works
fun.calc(90, 40)
fun.calc(90, NA)

#This, I have to add in a division by the length of the non-NA data values,
why?
fun.calc1(r1[,,1:length(r1)],r2[,,1:length(r2)], na.rm=T)

#My data are rasters, and I wish to produce the data in a raster for output
as a GeoTIff
#This produced no information
overlay(r1, r2, fun=fun.calc1, na.rm=T)

#Throws an error
overlay(r1[,,1], r2[,,1], fun=fun.calc1, na.rm=T)
#Error in (function (classes, fdef, mtable)  :
#  unable to find an inherited method for function 'overlay' for signature
'"numeric", "numeric"'

Thank you,

Katrina

	[[alternative HTML version deleted]]

