raster::focal returns incorrect values

275 views Asked by At

I am using the focal function from raster package v2.5-8 to get max value in a 3x3 window. I expect the edges of both rows/columns to return as NA, instead the output returned is 9,9,9. Is this correct ?

Example :

library(raster); require(rasterVis)
r <- raster(nrows=3, ncols=3)
r[] <- 1:ncell(r)
plot(r);text(r);
r.class <- focal(r, w=matrix(1,nrow=3,ncol=3), fun=max) 
plot(r.class); text(r.class);

Output:

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]    9    9    9
[3,]   NA   NA   NA

Expected Output:

       [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]   NA    9   NA
[3,]   NA   NA   NA
1

There are 1 answers

1
Robert Hijmans On BEST ANSWER

You get this result because the "left" and "right" sides (longitude = -180 or 180) of the globe are the same place.

library(raster)
r <- raster(nrows=3, ncols=3)
r[] <- 1:ncell(r)
as.matrix(r)

##     [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9

rf <- focal(r, w=matrix(1,nrow=3,ncol=3), fun=max) 
as.matrix(rf)

##     [,1] [,2] [,3]
## [1,]   NA   NA   NA
## [2,]    9    9    9
## [3,]   NA   NA   NA

The default CRS is lonlat

crs(r)

## CRS arguments:
## +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 

With a planar CRS you get what you expected:

crs(r) <- "+proj=utm +zone=1 +datum=WGS84"
rf2 <- focal(r, w=matrix(1,nrow=3,ncol=3), fun=max) 
as.matrix(rf2)

##     [,1] [,2] [,3]
## [1,]   NA   NA   NA
## [2,]   NA    9   NA
## [3,]   NA   NA   NA