2

When using terra::writeRaster, the maximum possible values allowed for writing depend on the datatype (INT1U, INT2S, INT2U...).

The documentation tells that "When writing integer values the lowest available value (given the datatype) is used [to store NA, I suppose] for signed types, and the highest value is used for unsigned values.". This should give the following range for unsigned types:

INT1U : 0-254 (2^8-1, minus one for NA storage)

INT2U : 0-65,534 (2^16-1, minus one for NA storage)

INT4U : 0-4,294,967,294 (2^32-1, minus one for NA storage)

However, for unsigned datatypes INT2U and INT4U, the maxima I observed on my machine do not fit these expectations:

INT2U : 65,532 INT4U : 4,294,967,292

Why this unexpected maximum values? I ask the question because it is not insignificant, for safe code writing, to exactly know these maximum values before writing files.

I am working under Windows 10. Here is a couple of code lines that I used to check:

library(terra)
terra version 1.3.4
Warning message:
package ‘terra’ was built under R version 4.0.5 

r <- rast(ncols=1, nrows=2)
values(r) <- c(65532,65533)

writeRaster(r,"test.tif",wopt=list(datatype="INT2U"))

t <- rast("test.tif")
values(t)
     lyr.1
[1,] 65532
[2,]   NaN

1 Answer 1

0

With the development version I now get the expected result

library(terra)
r <- rast(ncols=1, nrows=4)
values(r) <- 65533:65536

2-byte unsigned integer

x <- writeRaster(r,"test.tif", datatype="INT2U", overwrite=TRUE)
values(x)
#     lyr.1
#[1,] 65533
#[2,] 65534
#[3,]   NaN
#[4,]   NaN

x <- writeRaster(r,"test.tif", datatype="INT2U", NAflag=0, overwrite=TRUE)
values(x)
#[1,] 65533
#[2,] 65534
#[3,] 65535
#[4,]   NaN

4-byte unsigned integer

values(r) <- 4294967293:4294967296
x <- writeRaster(r,"test.tif", datatype="INT4U", overwrite=TRUE)
values(x)
#          lyr.1
#[1,] 4294967293
#[2,] 4294967294
#[3,]        NaN
#[4,]        NaN


x <- writeRaster(r,"test.tif", datatype="INT4U", NAflag=0, overwrite=TRUE,)
values(x)
#          lyr.1
#[1,] 4294967293
#[2,] 4294967294
#[3,] 4294967295
#[4,]        NaN
1
  • Thanks. It works perfectly. terra is evolving so fast that the development version is a must! Commented Jul 4, 2021 at 2:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.