Reputation: 11
I have generated a stack, 'class.stack', containing 175 rasters. Each cell in each raster can be one of four classes (represented by integers 0-3) or NA. NA should occur in the exact same positions across all 175 rasters as it represents a particular area that was not sampled.
I am trying to calculate a single raster from this stack, where class 0 is used if it is the majority class, otherwise the (integer) mean of 1-3 is taken. I first wrote the function below to use with 'calc':
class.cond <- function(x){
if (sum(x == 0) > sum(x != 0)) {0}
else {round(mean(x != 0)}}
I have learned that this won't work because 'calc' works in "chunks" of data, so it will not resolve as expected. I next tried to make individual rasters with the count of each class type across the stack, using this code:
count.zero <- calc(class.stack, na.rm=TRUE, fun=function(x){sum(x == 0)})
and so on for each remaining class. This gave the following error:
Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : cannot use this function. Perhaps add '...' or 'na.rm' to the function arguments?
I tried to resolve this by omitting NA as follows:
count.zero <- calc(class.stack, na.rm=TRUE, fun=function(x){
y <- as.numeric(na.omit(x))
sum(y == 0)})
This gave the same error. Where am I going wrong? It works if I run it over a vector containing the same kind of info.
test.vec <- c(NA, NA, 0, 0, 1, 2, 2, 3, 0, NA, 0, 1, 2)
mod.vec <- as.numeric(na.omit(test.vec))
print(mod.vec)
[1] 0 0 1 2 2 3 0 0 1 2
print(sum(mod.vec == 0))
[1] 4
print(sum(mod.vec == 2))
[1] 3
Upvotes: 1
Views: 30
Reputation: 11
I literally just had to pass the na.rm argument to the function, I guess. I didn't even do anything with it in the function, it just works now.
count.zero <- calc(class.stack, na.rm=TRUE, fun=function(x, na.rm){sum(x == 0)})
Upvotes: 0