I am calculating the maximum climatalogical water deficit from this study/scientific publication, using the Rcode that the authors publsihed with the study available here
It is a very simple code in which the input is monthly rainfall rasters, which I have downloaded from the Terraclimate product. After subtracting 100 mm/month (evapotranspiration) from each rainfall raster (month), a stack is created and the following function is used in calc()
wd = stack(month.rainfall)-100 # 100 is the evapotranspiration in mm/month
# MCWD Function
mcwd.f = function(x){
result= as.numeric(x)
for(i in 1:length(result)){
wdn = result[i]
wdn1 = result[i-1]
if(i==1){
if(wdn>0){ result[i]=0}
else{result[i]=wdn}
}
if(i!=1){
cwd = wdn1+wdn
if( cwd < 0){ result[i]=cwd}
else{result[i]=0}
}
}
return(result)
}
# Applying the Function
cwd = calc(wd, fun = mcwd.f)
However, after I run the line starting cwd I get the error Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : cannot use this function
Why do I have this error? How do I fix it?
I have looked at similar posts-1, 2,and have used na.rm=TRUE etc but I still get the same error. I also see some posts that say that the calc() is not very good, but I do not know how to solve this problem or find an alternative as I am using the code published by authors of the study I am replicating.
EDIT- I used a vector of 100 random numbers (with no NAs) to test the mcwd.f function and it works. So I think it is to do with having NA pixels, which I thought should get solved if I use na.rm=TRUE in the calc(), but it does not solve it.