# Conditional mean of rasterstack

I am trying to calculate the mean raster from a large RasterStack, with the following (using package raster):

``````raster_mean <- calc(raster_stack, conditonalmean)
``````

However, I do not want a standard mean, but I wish to add some conditions to the computation. I have written the following function (where three conditions appear, one is to remove null values and the others are numerical):

``````conditonalmean <- function(x, na.rm){
v = var(x,na.rm = na.rm)
mean(v[v>=-10 & v<=10])
``````

}

Which however returns the following error:

``````Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
``````

cannot use this function

Any suggestion?

Its failing because there's no default for `na.rm` in your function, and `calc` is calling it without a `na.rm` set. Try running your function on an arbitrary vector and you'll see what I mean:

``````> conditonalmean(1:10)
Error in var(x, na.rm = na.rm) :
argument "na.rm" is missing, with no default
``````

If you add a value for `na.rm` in the call to `calc` this will work:

``````> cm = calc(s, conditonalmean, na.rm=TRUE)
> cm
class       : RasterLayer
dimensions  : 4, 4, 16  (nrow, ncol, ncell)
``````

because the `na.rm` value to `calc` is passed through to calls to `conditonalmean` and so provide a value.

You can also fix it better by giving a default in your definition:

`````` conditonalmean =
function(x, na.rm=TRUE){
v = var(x,na.rm = na.rm)
mean(v[v>=-10 & v<=10])
}
``````

Also, you should probably check the spelling! Your function is "conditonal" mean!