I've used the focalWeight
function in R's raster
package to create focal "moving window" weight matrices for tens of thousands of images. On a few dozen of the images the function does not behave as expected. I expect a 3x3 matrix, but am returned a 1x3 matrix.
Upon digging into the problem I think it is due to the floor
function which is called internally.
I'll demonstrate the problem below (I have a raster named r
). I'm running code from .circular.weight
res(r) # raster resolution is 1
#[1] 1 1
rs <- res(r)
d <- 1 # window diameter is 1
nx <- 1 + 2 * floor(d/rs[1]) # number of columns is 3
nx # this is expected
#[1] 3
ny <- 1 + 2 * floor(d/rs[2]) # number of rows is 1
ny # this is unexpected
#[1] 1
1 + 2 * floor(d/rs[2])
#[1] 1
2 * floor(d/rs[2])
#[1] 0
floor(d/rs[2]) # the floor of 1 is 0
#[1] 0
d/rs[2]
#[1] 1
floor(1) # but the floor of 1 should be 1
#[1] 1
res(r) == 1 # the resolution appears to be 1, 1
# [1] 1 1
res(r) == 1 # but it isn't really
# [1] TRUE FALSE
?floor
says that unexpected results like this have been seen before. It says, "It is normally necessary to use a tolerance."
How do I use a tolerance?
How can I fix the focalWeight
function?