r-quantities / units

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

units and lm/glm not playing well together #366

Closed hugomflavio closed 4 months ago

hugomflavio commented 4 months ago

Hi!

I'm implementing units for some internal functions and I've stumbled upon an issue when running linear models on variables that contain units. The function glm() won't run at all, and while lm() works, asking for a summary() will fail, and predict() silently drops the units. Here's a minimal example:

# minimal example
library("units")

x <- data.frame(A = rnorm(20), 
                B = 1:20)
units(x$A) <- "umol/L"
units(x$B) <- "s"

# glm() does not work
m1 <- glm(A ~ B, 
          data = x) 
# Error in Ops.units(eta, offset) : 
#   both operands of the expression should be "units" objects

# lm() partly works
m2 <- lm(A ~ B, 
         data = x) 
summary(m2)
# Error in Ops.units(mean(f)^2, var(c(f))) : 
#   both operands of the expression should be "units" objects

predict(m2) # units dropped

# removing units makes it work, as expected
m3 <- glm(as.numeric(A) ~ as.numeric(B),
          data = x) 
summary(m3)

A current work-around appears to be to drop the units prior to running the model, and then re-inserting them on the model outputs. It would be great if these functions could tolerate/carry the units along though.

Thanks for keeping this package up and running!

Enchufa2 commented 4 months ago

This is not currently supported, and it's... complicated. Not in the roadmap at the moment. See this post.

hugomflavio commented 4 months ago

Ah, I was afraid that would be the answer. That post is very helpful though and will give me what I need for my very specific case. Thanks!