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
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)