Skip to content

Compatibility with units package #1737

Open
@wilfinc

Description

@wilfinc

The units package provides the ability to set and then convert values between different units (primarily through units::set_units()). While terra has a units() function, this appears to just fill a character slot in the spat raster object and does not convert values when this variable is changed. Would it be possible to integrate these functions?

Looking through the terra GitHub repo I can see mentions of 'set_units' but I'm not familiar enough with package coding of this type to understand this fully.

Example code:

library(terra)
library(units)

### Create a dummy SpatRaster
r <- rast(nrows = 10, ncols = 10)
r[] <- 100
r

### Set unit with terra::units
units(r) <- 'kg'
global(r, mean)

### Change this value and we see the SpatRaster values do not change. 
units(r) <- 'g'
global(r, mean)

### units::set_units appears to work on SpatVector values (not on SpatRaster objects themselves) but the units are lost when these values are added back to the SpatRaster. 
### set units to values
r[] <- set_units(r[], 'kg')
units(r)
global(r, mean)
### Attempting to change the units does not work as the previous units data is not retained. 
r[] <- set_units(r[], 'g')
units(r)
global(r, mean)

### When SpatRaster values are not moved back into a SpatRaster, the units::set_units() conversions do work.
v_values <- r[]
mean(set_units(v_values, 'kg'))
mean(set_units(set_units(v_values, 'kg'), 'g'))

Running terra version 1.8.15, units version 0.8.5, and R version 4.4.2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions