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
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"
-
1What 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– jim2016年01月02日 16:55:49 +00:00Commented Jan 2, 2016 at 16:55
-
1
-
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.ecologist1234– ecologist12342018年09月19日 14:08:45 +00:00Commented Sep 19, 2018 at 14:08
-
2How are you saving the raster? I'd guess you are not specifying
datatype="INT4U"
or some other integer specification inwriteRaster
. The default is"FLT4S"
.Spacedman– Spacedman2018年09月19日 14:16:07 +00:00Commented Sep 19, 2018 at 14:16 -
1yes, and notice its
datatype
inwriteRaster
butdataType
to get the type of a raster...Spacedman– Spacedman2018年09月19日 21:50:56 +00:00Commented Sep 19, 2018 at 21:50