Reputation: 930
I want to apply funtion on stack each layer and return a stack.
library(raster)
r1 <- raster(vals=1:20,nrow=4,ncols=5)
r2 <- raster(vals=2:21,nrow=4,ncols=5)
r3 <- raster(vals=3:22,nrow=4,ncols=5)
stk <- stack(r1,r2,r3)
func <- function(x){
calc(x,function(y){
ifelse(y>10,0,y)
})
}
I apply func
on each layer by using lapply
lapply(stk,func)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘calc’ for signature ‘"integer", "function"’
It seems lapply
slice stk
as stk[1]
stk[2]
..., but the actual layer is stk[[1]]
,stk[[2]]
....
And use stackApply
:
stackApply(stk,indices=1:3,fun=func)
Error in FUN(newX[, i], ...) : unused argument (na.rm = na.rm)
Upvotes: 2
Views: 780
Reputation: 48241
It looks like you can use calc
alone:
stack(calc(stk, function(y) ifelse(y > 10, 0, y)))
# class : RasterStack
# dimensions : 4, 5, 20, 3 (nrow, ncol, ncell, nlayers)
# resolution : 72, 45 (x, y)
# extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# names : layer.1, layer.2, layer.3
# min values : 0, 0, 0
# max values : 10, 10, 10
Upvotes: 3