0
votes

I am trying to run a 'calc' function in R and I can't seem to find a way to obtain the coordinates of the cell that is being processed. What I'm trying to do is simple : Using the 'calc' function on a binary raster (0 and 1)-- If the raster value is '0', then change to 'NA'. If the raster value is '1', then apply a series of processes for which I will need to cell coordinates to be stored into variables.

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 message :

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"’ 

Thanks everyone!

1
Are you importing coordinates function from some library or did you write it yourself?eonurk
It's a function defined from the package 'raster'.Antoine Prince
The function takes an object to calculate the coordinates, not an integer or vector of integers. That might be the problem you are experiencing.eonurk
Yes, that is exactly the problem. The variable 'cell' only contains its value, so '1'. But I was wondering if anyone had an idea as to how I could get its coordinates.Antoine Prince

1 Answers

0
votes

That is not possible. But you can make a RasterLayer with the x and y coordinates and used these in calc.

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

And then

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