I'm working with raster data in the {terra} package. I want to store my data in an optimum datatype for storage and speed. So for example, I run a function, and it outputs integer data between 1 and 200. So I save the raster as INT1U which has range 0 to 255, rather than as FLT4S, which can deal with decimals and a much large range. My query though is that if I have data which does not match the type I am writing, it becomes NA. I'd prefer an error (as it tells me there is data I am not expecting in the output). Any thoughts on how to do that? My current effort:
Illustration of my problem:
library(terra)
test_rast <- rast(ncol = 2, nrow = 2, vals = c(-10, 50, 100, 10000000000))
test_rast <- writeRaster(test_rast, 'test.tif', wopt = list(datatype = 'INT1U'), overwrite=TRUE)
values(test_rast)
lyr.1
[1,] NaN
[2,] 50
[3,] 100
[4,] NaN
One solution I thought was to test. Something like this:
library(terra)
test_rast <- rast(ncol = 2, nrow = 2, vals = c(-10, 50, 100, 10000000000))
int1u_min <- 0
int1u_max <- 254
if (minmax(test_rast)[[1]] >= int1u_min & minmax(test_rast)[[2]] < int1u_max) {
test_rast <- writeRaster(test_rast, 'test.tif', wopt = list(datatype = 'INT1U'), overwrite=TRUE)
} else {
stop()
}
As you can see it is not a very elegant solution. Plus I will have to manually set the acceptable min and max of each raster datatype range. Probably by copying this table into my script.
https://www.rdocumentation.org/packages/raster/versions/3.5-15/topics/dataType
Is there a better way?
With terra >= 1.6-6 you now get a warning.
library(terra)
r <- rast(ncol = 2, nrow = 2, vals = c(-10, 50, 100, 10000000000))
r <- writeRaster(r, 'test.tif', datatype = 'INT1U', overwrite=TRUE)
#Warning message:
#[writeRaster] detected values outside of the limits of datatype INT1U