I am trying to take multiple raster files, add them together, and write the resulting raster file to disk. However, I've noticed that each time I've done this the resulting raster.img file is ~877 mb in size, while the individual raster files I am adding together are no bigger than 4 mb. Additionally, sometimes I'm combining 3 rasters into 1, sometimes I'm combining 10 rasters in to 1. No matter how many I start with, the resulting raster files are all the same size.
Here is some example code for how I'm adding the rasters together and writing to file
library(raster)
r1 <- r2 <- r3 <- raster(nrow=10, ncol=10)
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
values(r3) <- runif(ncell(r3))
combined <- r1 + r2 + r3
writeRaster(combined, "data/filename.img", overwrite = T)
Based on a similar question here I checked that the datatypes of my input rasters and the combined raster were the same, and they were. All of them are FLT4S. The resulting values in the combined raster don't seem wrong - I have no negative values or absurdly high values or anything.
Is there something else that I'm missing? Could there be some quality of the rasters I'm starting with that I'm overlooking that would affect this?
Data type can plays a role:
x <- writeRaster(combined, "filename1.img", datatype='FLT4S', overwrite=TRUE)
y <- writeRaster(combined, "filename2.img", datatype='INT2S', overwrite=TRUE)
file.size("filename1.img")
#[1] 23249
file.size("filename2.img")
#[1] 15057
But you state that all files are FLT4S
. And given the very large (> 200 times) difference in file size, something else must be going on. The input files are probably compressed. You can compress the output files (see manual)
z <- writeRaster(combined, "filename3.img", datatype='FLT4S', options="COMPRESSED=YES", overwrite=TRUE)
file.size("filename3.img")
#[1] 7429
That is about 3 times smaller that without compression. Perhaps the original data can be compressed more, but it still seems unlikely to get 200 times reduction.