# Resample raster but keep sum of total cell values the same

I am trying to resample a raster to a finer resolution, matching the resolution of my raster of interest. The problem is, my raster I'm resampling is a population raster. When I resample, the total values of all of the cells increases in proportion to the increase in resolution. Is there a way I can resample my raster and keep the sum of all cells equal?

Example code:

``````r1 <- raster(ncol=10,nrow=10)
r2 <- raster(ncol=4,nrow=4)
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
r2_res <- resample(r2,r1,method='bilinear')
#sum(r2_res) should equal sum(r2)

cellStats(r2_res,sum,na.rm=T) - cellStats(r2,sum,na.rm=T)==0

[1] FALSE

``````

You are assuming population is equally distributed in each cell, thus, we shall divide the original cell population by the number of finer resolution cells that fit in the original:

``````library(terra)
r <- rast(nrows=8, ncols=6, xmin=0, xmax=10, ymin=0, ymax=10) # finer
pop <- rast(nrows=4, ncols=3, xmin=0, xmax=10, ymin=0, ymax=10) # coarser; the population rast
values(pop) = 1:ncell(pop)

x = resample(pop, r, method = "near" ) # we pass raw values to finer raster
wr = x*(prod(res(x)/res(pop)))         # we divide the original cell by the resolution

sum(wr[]) == sum(s[])
# TRUE
res(x) == res(r)
# TRUE

plot(pop)
text(pop)
text(wr, col = "red", digits = 3)
``````