r-quantities / units

Measurement units for R
https://r-quantities.github.io/units
175 stars 28 forks source link

power operations are limited #327

Closed lexcomber closed 2 years ago

lexcomber commented 2 years ago

I am having problems undertaking power operations (such as distance decay calculations) when packages with dependencies on units like sf are loaded into the R environment. The example below requires a fresh R session.

## load some data - a data frame
download.file("https://www.dropbox.com/s/0xgsmmjshudsy06/sim_tab.RData?dl=1", "sim_tab.RData")
load("sim_tab.RData")
head(sim_tab)

# calculate some exponential distance decay
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
head(sim_tab)

# load tidyverse - no problem
library(tidyverse)
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
# or piped
sim_tab <- sim_tab %>% mutate(Flow_Factor=(Floorspace^1.05)*2^(-Dist/0.2))
head(sim_tab)

# load sf - problem - also if units is loaded
# generates an error message
#> Error in Ops.units(2, (-sim_tab$Dist/0.2)) : 
#>  power operation only allowed with logarithmic unit
library(sf)
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
sim_tab <- sim_tab %>% mutate(Flow_Factor=(Floorspace^1.05)*2^(-Dist/0.2))
lexcomber commented 2 years ago

I think I have resolved this with the drop_units function from the units package:

## load some data - a data frame
download.file("https://www.dropbox.com/s/0xgsmmjshudsy06/sim_tab.RData?dl=1", "sim_tab.RData")
load("sim_tab.RData")
head(sim_tab)

# calculate some exponential distance decay
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
head(sim_tab)

# load tidyverse - no problems
library(tidyverse)
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
# or piped
sim_tab <- sim_tab %>% mutate(Flow_Factor=(Floorspace^1.05)*2^(-Dist/0.2))
head(sim_tab)

# load sf - problem
library(sf)
sim_tab$Flow_Factor=as.vector( (sim_tab$Floorspace^1.05)*2^(-sim_tab$Dist/0.2) )
sim_tab <- sim_tab %>% mutate(Flow_Factor=(Floorspace^1.05)*2^(-Dist/0.2))

# resolution: use the drop_units() function
library(units)
sim_tab <- 
  sim_tab %>% 
  mutate(Dist = drop_units(Dist)) %>%  
  mutate(Flow_Factor=(Floorspace^1.05)*2^(-Dist/0.2))
head(sim_tab)