r - 如何在每一层应用光栅堆栈对象?

标签 r

我想在堆栈的每一层上应用函数并返回一个堆栈。

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)
  })
}

我使用lapply在每一层上应用func

lapply(stk,func)
Error in (function (classes, fdef, mtable)  : 
unable to find an inherited method for function ‘calc’ for signature ‘"integer", "function"’ 

看起来lapply切片stkstk[1]stk[2]...,但是实际层是 stk[[1]],stk[[2]]....

并使用stackApply:

stackApply(stk,indices=1:3,fun=func)
Error in FUN(newX[, i], ...) : unused argument (na.rm = na.rm)

最佳答案

看起来您可以单独使用calc:

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 

关于r - 如何在每一层应用光栅堆栈对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684550/

相关文章:

r - Quantmod Heikin-Ashi 绘图不可用

r - 循环重命名 R 数据帧中的字段

r - 为什么在集群代码中没有NA简介?

r - 检查一个向量中的值是否小于另一向量(不同长度)中的值,并用 Y/N 答案填充表格

r - Shiny 的分层嵌套checkboxGroupInput

在 Shiny 上多个场景的 RSelenium 并发用户

r - 使用 R 中的 spplot 设置 NA 值的颜色

r - 向量作为 `data.table` 中的条目

r - 识别散点图中的异常值

R 从一组字符串数据创建唯一键