[GIS] Round() does not return an integer raster in R

rraster

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?

Best Answer

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"
Related Question