4

I wish to change the resolution and extent of a raster. I have tried to combine in different ways extend, aggregate, resample but unsuccessfully… below is a code I wrote to get the right resolution and extent, but as a consequence, the total pixel values are changed (and the difference can be quite large in some cases...). There are quite a lot on posts online on raster extents and resolutions, but I haven't managed to solve my problem. Is there a way I can change the resolution and extent while minimizing changes in total pixel values (cellStats(r, sum))? Thank you very much.

library(raster)

#sample rasters
r <- raster(extent(-180,179.9999, -55.91668 , 83.58326))
res(r)<-c(0.5/6, 0.5/6)
r <- setValues(r, runif(ncell(r)))
cellStats(r, sum) #3615229

temp_extent <- raster(extent(-180,180, -90 , 90))
res(temp_extent)<-c(0.5, 0.5)

# to get resolution (0.5, 0.5)
r1 <- aggregate(r, fact=6, fun=sum)
cellStats(r1, sum) #3615229
r1
# to get extent (-180,180,-90,90)
r2 <- resample(x= r1, y=temp_extent, method="bilinear") # what I am hoping is for NA to fill the added pixels
cellStats(r2, sum) #problem: gives different total value: 3615916
r2
Cecile
  • 527
  • 5
  • 22
  • 2
    If you resample, you will necessarily change the pixel values, right? – bdemarest Dec 01 '18 at 08:08
  • @bdemarest thanks, I have edited my question. I wonder whether there is a way I can change both extent and resolution while minimizing changes in cellStats(r, sum) – Cecile Dec 01 '18 at 08:36

1 Answers1

3

Using Nearest Neighbour resampling in the last passage should do the trick:

library(raster)
#> Loading required package: sp

#sample rasters
r <- raster(extent(-180,179.9999, -55.91668 , 83.58326))
res(r)<-c(0.5/6, 0.5/6)
set.seed(1234)
r <- setValues(r, runif(ncell(r)))
cellStats(r, sum)
#> [1] 3615109

temp_extent <- raster(extent(-180,180, -90 , 90))
res(temp_extent)<-c(0.5, 0.5)

# to get resolution (0.5, 0.5)
r1 <- aggregate(r, fact=6, fun=sum)
cellStats(r1, sum)
#> [1] 3615109

# to get extent (-180,180,-90,90)
r2 <- resample(x= r1, y=temp_extent, method="ngb") 
cellStats(r2, sum)
#> [1] 3615109

all.equal(cellStats(r, sum), cellStats(r2, sum))
#> [1] TRUE

Created on 2018-12-01 by the reprex package (v0.2.1)

lbusett
  • 5,801
  • 2
  • 24
  • 47
  • Thank you @Ibusett. I thought I shouldn't use ngb for non categorical variables... but indeed it works! Thanks – Cecile Dec 01 '18 at 21:46