rspatial / raster

R raster package https://rspatial.github.io/raster/reference/raster-package.html
GNU General Public License v3.0
161 stars 52 forks source link

Different cell numbers output by extract() depending on value of parameter 'exact' #295

Closed imprompt closed 2 years ago

imprompt commented 2 years ago

In the following example, the cell numbers output by the 2nd extract call (exact=T) contain an error. The first call to extract (exact=F) looks correct.

library(raster)

normalizeWeights <- F

# geometries
r <- raster(nrows=2, ncols=2, xmn=0, xmx=200, ymn=0, ymx=200, vals=10*(1:4))
p1 <- Polygon(cbind(c(90,160,160,90,90), c(30,30,110,110,30)), hole=F)
p2 <- Polygon(cbind(c(180,190,190,180,180), c(180,180,190,190,180)), hole=F)
p3 <- Polygon(cbind(c(40,60,60,40,40), c(140,140,160,160,140)), hole=F)
poly <- spPolygons(p1, p2, p3, crs=crs(r))

# plot
plot(r)
plot(poly, add=T)

# overlay
extract(r, poly, exact=F, weights=T, normalizeWeights=normalizeWeights, cellnumbers=T, df=T) # correct
extract(r, poly, exact=T, weights=T, normalizeWeights=normalizeWeights, cellnumbers=T, df=T) # incorrect
rhijmans commented 2 years ago

Thank you very much for reporting this and for the good example. I now get:

extract(r, poly, exact=FALSE, weights=TRUE,  normalizeWeights=F, cellnumbers=T, df=T)
#        ID cell layer weight
#X        1    1    10   0.01
#X.1      1    2    20   0.06
#X.2      1    3    30   0.07
#X.3      1    4    40   0.42
#layer    2    2    20   0.01
#layer.1  3    1    10   0.04

extract(r, poly, exact=TRUE,  weights=TRUE, normalizeWeights=F, cellnumbers=T, df=T)
#  ID cell layer weight
#1  1    1    10   0.01
#2  1    2    20   0.06
#3  1    3    30   0.07
#4  1    4    40   0.42
#5  2    2    20   0.01
#6  3    1    10   0.04

Which is the same as what I get with "terra" (the replacement of "raster"):

library(terra)
x <- rast(r)
v <- vect(poly)
extract(x, v, exact=TRUE, cell=TRUE)
#  ID layer cell fraction
#1  1    10    1     0.01
#2  1    20    2     0.06
#3  1    30    3     0.07
#4  1    40    4     0.42
#5  2    20    2     0.01
#6  3    10    1     0.04