[R-sig-Geo] difficulties on applying a function trough calc on a rasterstack

Pep SD pep.bioalerts at gmail.com
Fri Aug 5 19:21:23 CEST 2016


Hello everyone,

I feel this may be R-raster 101 but I can't really find the solution to
this.

I want to apply a function over a rasterstack, so that it outputs a raster
layer in which the function has been applied to each cell of the
rasterstack.


#function to pass

mfri.test <- function (a){
  a2 <- a[a>0]
  a2 <- unique (a2)
  a2 <- a2[order(a2)]
  if (length (a2)==0){b<-0}else{
    if (length (a2)==1){b<-c(a2)}
    if (length (a2)>1) {

      b <- lapply (1:(length(a2)-1), function (m){
        a2[m+1]-a2[m]
      })
      b<- unlist (b)

    }
    if (a2[length(a2)]!=85){m <- c(85-a2[length(a2)]); b <- c(b,m) }}
  return (mean(b))
}


#now let's try it on a vector -- ideally mm represents a single cell values
on a rasterStack

mm <-c(0,3,4,65,89)
mfri.test(a=mm)
[1] 20.5


#now let's try it with a small raster

r <- raster (matrix(ncol=1,data = 1,nrow = 1))
r2 <- raster (matrix(ncol=1,data = 21,nrow = 1))
r3 <- raster (matrix(ncol=1,data = 72,nrow = 1))
rst <- stack(r,r2,r3)
calc (rst,function (x) { mfri.test(x)},na.rm=T )

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
  cannot use this function. Perhaps add '...' or 'na.rm' to the function
arguments?

# Is it because the function is poorly written? what am I doing wrong?

Thank you for your help,
Pep

P.S. SessionInfo below



> sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2008 R2 x64 (build 7601) Service Pack 1

locale:
  [1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United
States.1252
[3] LC_MONETARY=English_United States.1252
LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
  [1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
  [1] raster_2.3-40 sp_1.1-1

loaded via a namespace (and not attached):
  [1] tools_3.3.0     grid_3.3.0      lattice_0.20-33

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list