Search code examples
rraster

Get summary vectors of raster cell centers in R


I want to extract summary vectors that contain the coordinates for the centers of the different cells in a raster. The following code works but I believe involves an n-squared comparison operation. Is there a more efficient method? Not seeing anything obvious in {raster}'s guidance.

require(raster)
r = raster(volcano)
pts = rasterToPoints(r)
x_centroids = unique(pts[,1])
y_centroids = unique(pts[,2])

Solution

  • To get the centers of the raster cells, you should use the functions xFromCol, yFromRow and friends (see also the help pages)

    In this case, you get exactly the same result as follows:

    require(raster)
    r <- raster(volcano)
    x_centers <- xFromCol(r)
    y_centers <- yFromRow(r)
    

    Note that these functions actually don't do much else but check the minimum value of the coordinates and the resolution of the raster. From these two values, they calculate the sequence of centers as follows:

    xmin(r) + (seq_len(ncol(r)) - 0.5) * xres(r)
    
    ymin(r) + (seq_len(nrow(r)) - 0.5) * xres(r)
    

    But you better use the functions mentioned above, as these do a bit more safety checks.