jsta
jsta

Reputation: 3412

extract from raster that is based on spatialpoints extent

Lets say I produce a raster based on the extent of a SpatialPoints object.

    r<-setExtent(r,extent(pts))
    identical(extent(r),extent(pts))==TRUE

But now if I change the resolution with res why is it that:

    identical(extent(r),extent(pts))==FALSE

Upvotes: 1

Views: 77

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47601

This only happens in some cases (if you cannot divide without remainder the x/y extent by the the number of columns/rows implied by the new resolution.) A change of resolution leads to a new number of columns and rows of a certain width/height. If these do not exactly fit within the extent, the extent needs to be adjusted. Simple example:

library(raster)
r <- raster(xmn=0, xmx=5, ymn=0, ymx=5, res=1)
r
#class       : RasterLayer 
# dimensions  : 5, 5, 25  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent      : 0, 5, 0, 5  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 

So if you change the resolution of 'r' to, for example, 2.5 or 0.5, the extent stays the same:

res(r) <- 2.5
r
# class       : RasterLayer 
# dimensions  : 2, 2, 4  (nrow, ncol, ncell)
# resolution  : 2.5, 2.5  (x, y)
# extent      : 0, 5, 0, 5  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 

But if you change it to, for example, 3, the extent needs to change as you cannot fit multiples of 3 (rows/columns) into an extent of 0..5. So the extent needs to be reduced to 0..3 or expanded to 0..6 (or -1..5). The latter is the smaller change, so that is what happens.

r <- raster(xmn=0, xmx=5, ymn=0, ymx=5, res=1)
res(r) <- 3
r
class       : RasterLayer 
dimensions  : 2, 2, 4  (nrow, ncol, ncell)
resolution  : 3, 3  (x, y)
extent      : 0, 6, -1, 5  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 

Upvotes: 3

Related Questions