[R] raster::cellFromXY behaviour

Jae Choi choi.jae.seok at gmail.com
Mon Nov 9 17:18:02 CET 2015

Hi users of raster:

When a point lands within a raster cell, the cell is correctly identified.
But when a point lands on the border between two adjacent raster cells,
cell identity seems to be inconsistent. We are wondering if this is an

Example code follows to demonstrate our question:



# simple raster with integers fill
r0 <- raster( xmn=xmn, ymn=ymn, xmx=xmx, ymx=ymx, res=res )
r0[] <- 1:ncell(r0)

# choose points along a horizontal band:
locx = seq(xmn, xmx, res)
xy1 <- cbind( locx + res/2, rep(ymn+res+res/2, dim(r)[1] ) ) # center of a
raster cell
xy2 <- cbind( locx,         rep(ymn+res+res/2, dim(r)[1] ) ) # on x-boundary
xy3 <- cbind( locx + res/2, rep(ymn+res, dim(r)[1] ) ) # on y-boundary
xy4 <- cbind( locx,         rep(ymn+res, dim(r)[1] ) ) # on a corner

# plots to visualize selected points
cid1 = cellFromXY(r, xy1); r = r0; r[cid1] <- NA; plot(r)
cid2 = cellFromXY(r, xy2); r = r0; r[cid2] <- NA; plot(r)
cid3 = cellFromXY(r, xy3); r = r0; r[cid3] <- NA; plot(r)
cid4 = cellFromXY(r, xy4); r = r0; r[cid4] <- NA; plot(r)

The expectation would have been to see no banding as seen in xy1 and xy3.
But xy2 and xy4 seem to skip a few cells. Not sure why?


	[[alternative HTML version deleted]]

More information about the R-help mailing list