Cooper Springer
Cooper Springer

Reputation: 11

How to permanently round values in a raster layer, matrix, or array, to write to a new file using r studio?

I am trying to round either round a 3 dimensional matrix or several raster layers that will be made into a 3 dimensional matrix to 2 decimal places to make a new netcdf file that will take up less memory.

Using the round function as such:

newmatrix <- round(oldmatrix, 2)

only seems to round values superficially for display. Opening newmatrix and extracting values from it after adding it to a new file returns the unrounded values from oldmatrix. This is despite the fact that values extracted from newmatrix before adding it to a new file will be rounded to 2 decimal places as is supposed to be. The same thing happens if I round off the raster layers before creating a new matrix with them.

What function can I use to permanently round off my matrix's or raster's values to write to a new file rounded?

Upvotes: 1

Views: 503

Answers (1)

Robert Davy
Robert Davy

Reputation: 910

NetCDF doesn't have a fixed precision format that would save space in the way you are expecting. (See here for data types). The usual way of saving space is to encode as a short integer and set the variable attributes scale_factor and add_offset.

In your case, you would multiply by 100, convert to short, and have scale_factor=0.01. Doing this in R is probably a lot of work, but nco utility would handle it in a few lines. Let's say you have a variable called rh.

ncap2 -v -s 'rh=short(100*rh);' in.nc out.nc
ncatted -O -h -a add_offset,rh,o,f,0 out.nc
ncatted -O -h -a scale_factor,rh,o,f,0.01 out.nc

Equivalently, this can be done in one line using

ncap2 -v -O -s 'rh=pack_short(rh, 0.01, 0.0);' in.nc out.nc

If you are looking to save memory when reading a variable into R, you might be disappointed as it will just be converted back into a float upon reading.

Upvotes: 3

Related Questions