6

I want to convert the datatype of a raster to integer. For example:

x <- raster(nrow=10,ncol=10)

its datatype is float

dataType(x)
[1] "FLT4S"

then I round the pixel values of x by

 y <- round(x)
 dataType(y)
 [1] "FLT4S"

How can I change the dataType of y to int?

1 Answer 1

10

Just tell it:

> dataType(y)="INT4S"
> dataType(y)
[1] "INT4S"

read the help for dataType to make sure you are doing the right thing though. This doesn't change R's internal storage mode:

> x=raster(nrow=10,ncol=10)
> x[]=runif(100)
> mean(x[])
[1] 0.5444336
> dataType(x)="INT4U"
> dataType(x)
[1] "INT4U"
> mean(x[])
[1] 0.5444336

If what you really meant to ask was "how do I change the underlying storage type of raster data" then possibly you can just change the storage mode of the appropriate values:

> r = raster(ncol=100,nrow=100)
> r[]=rnorm(100*100)
> object.size(r)
86460 bytes
> storage.mode(r[]) = "integer"
> object.size(r)
46460 bytes
> r[][1:10]
 [1]  0  0 -1 -1 -1 -1  0  0 -2  0

Or just coerce the values:

> r[]=rnorm(100*100)
> storage.mode(r[])
[1] "double"
> r[]=as.integer(r[])
> storage.mode(r[])
[1] "integer"
6
  • 1
    What I want is to actually change the internal storage mode so to reduce memory requirements. It is not efficient to reserve 4 bytes in memory for a pixel when 1 byte would be sufficient.
    – jim
    Jan 2, 2016 at 16:55
  • 1
    Done, see edits
    – Spacedman
    Jan 2, 2016 at 17:03
  • Hmm. When I try any of these, then import a raster saved as a .tif from R into Arcmap, I am left with a floating point raster still. Sep 19, 2018 at 14:08
  • 2
    How are you saving the raster? I'd guess you are not specifying datatype="INT4U" or some other integer specification in writeRaster. The default is "FLT4S".
    – Spacedman
    Sep 19, 2018 at 14:16
  • 1
    yes, and notice its datatype in writeRaster but dataType to get the type of a raster...
    – Spacedman
    Sep 19, 2018 at 21:50

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.