Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compatibility with units package #1737

Open
wilfinc opened this issue Feb 5, 2025 · 0 comments
Open

Compatibility with units package #1737

wilfinc opened this issue Feb 5, 2025 · 0 comments

Comments

@wilfinc
Copy link

wilfinc commented Feb 5, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant