title: raster::calc() error in calctest(x[1:5]) with userdefined function
body: <p>I am calculating the maximum climatalogical water deficit from this <a href="https://agupubs.onlinelibrary.wiley.com/doi/10.1029/2006GL028946" rel="nofollow noreferrer">study/scientific publication</a>, using the Rcode that the authors publsihed with the study available <a href="https://zenodo.org/record/2652658#.XukFTefTXb2" rel="nofollow noreferrer">here</a></p>
  
  <p>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()</p>
  
  <pre><code>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&gt;0){ result[i]=0}
    else{result[i]=wdn}
  }
  
  if(i!=1){
    cwd = wdn1+wdn
    if( cwd &lt; 0){ result[i]=cwd}
    else{result[i]=0}
     }
   }
  
  return(result)  
   }
  
  
  # Applying the Function
  cwd = calc(wd, fun = mcwd.f)
  </code></pre>
  
  <p>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</p>
  
  <p>Why do I have this error? How do I fix it?</p>
  
  <p>I have looked at similar posts-<a href="https://stackoverflow.com/questions/42327823/error-using-calc-function-cannot-use-this-function">1</a>, <a href="https://gis.stackexchange.com/questions/289078/conditional-mean-of-rasterstack">2</a>,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. </p>
  
  <p>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. </p>