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

Would it be useful to work directly with objects of class model_fit, as produced by tidymodels? #1194

Closed
davidkane9 opened this issue Aug 22, 2024 · 1 comment

Comments

@davidkane9
Copy link

Consider:

library(tidymodels)
library(marginaleffects)

mod <- linear_reg() |> 
  fit(mpg ~ hp + drat, data = mtcars)

predictions(mod$fit) # works
#> 
#>  Estimate Std. Error     z Pr(>|z|)     S 2.5 % 97.5 %
#>      23.4      0.671 34.89   <0.001 883.6 22.10   24.7
#>      23.4      0.671 34.89   <0.001 883.6 22.10   24.7
#>      24.1      0.720 33.40   <0.001 810.2 22.65   25.5
#>      19.6      0.999 19.59   <0.001 281.4 17.61   21.5
#>      16.5      0.735 22.47   <0.001 369.1 15.09   18.0
#> --- 22 rows omitted. See ?avg_predictions and ?print.marginaleffects --- 
#>      22.7      0.630 35.96   <0.001 938.3 21.42   23.9
#>      16.9      1.668 10.16   <0.001  78.1 13.68   20.2
#>      18.7      0.625 29.97   <0.001 653.3 17.51   20.0
#>      10.1      1.810  5.57   <0.001  25.2  6.53   13.6
#>      24.5      0.787 31.09   <0.001 702.5 22.91   26.0
#> Columns: rowid, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, mpg, hp, drat 
#> Type:  response

predictions(mod) # fails
#> Error: Unable to extract the data from model of class `_lm`. This can happen in
#>   a variety of cases, such as when a `marginaleffects` package function is
#>   called from inside a user-defined function, or using an `*apply()`-style
#>   operation on a list. Please supply a data frame explicitly via the
#>   `newdata` argument.

Created on 2024-08-22 with reprex v2.1.0

This is all working as it is supposed to. But my students (and me) were expecting marginaleffects functions to work directly on objects produced by fitting tidymodels. Fortunately, I think this functionality would be easy to add by just checking to see if the value passed in for the model argument is of class model_fit. If it is, we just pull out the $fit.

If this seems reasonable, I could submit a PR.

@vincentarelbundock
Copy link
Owner

@davidkane9 thanks for raising this issue. Makes sense.

I opened a PR with a potential fix, but I have not tested it extensively. If you have time, check it out and let me know if it works as expected.

vincentarelbundock added a commit to kkmann/marginaleffects that referenced this issue Aug 31, 2024
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

2 participants