首页 > 解决方案 > 使用 R 中的 'calc' 函数获取栅格单元坐标

问题描述

我正在尝试在 R 中运行“计算”函数,但似乎找不到获取正在处理的单元格坐标的方法。我要做的很简单:在二进制栅格(0 和 1)上使用“calc”函数——如果栅格值为“0”,则更改为“NA”。如果栅格值为“1”,则应用一系列过程,我需要将单元坐标存储到变量中。

processAllCells = function(cell) {
  if (cell == 0) {
    cell = NA
    return(cell) 
  }
  else {
    cellCoords = coordinates(cell) ### This is what I'm trying to do. This does not work. See the error message.
    ### Here will go further processes using the cell coordinates.
    return(cell)
  }
}

outputRaster = calc(lake, processAllCells)

错误信息 :

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘coordinates’ for signature ‘"integer"’
In addition: Warning message:
In if (cell == 0) { :

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

感谢大家!

标签: rcoordinatesrasterr-rastercalc

解决方案


这是不可能的。但是您可以使用 x 和 y 坐标制作一个 RasterLayer 并在calc.

library(raster)
r <- raster(nrow=10, ncol=10, values=1:100)
x <- init(r, "x")
y <- init(r, "y")

接着

s <- stack(r, x, y)
#x <- calc(s, your-function)

推荐阅读