Skip to content

Commit 74cb53e

Browse files
authored
Deal with / fix tidy() method in the _marginaleffects_ methods for model_parameters() (#1157)
* Deal with / fix `tidy()` method in the _marginaleffects_ methods for `model_parameters()` Fixes #1156 * comment
1 parent 63c2ff8 commit 74cb53e

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

DESCRIPTION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Type: Package
22
Package: parameters
33
Title: Processing of Model Parameters
4-
Version: 0.28.0.7
4+
Version: 0.28.0.9
55
Authors@R:
66
c(person(given = "Daniel",
77
family = "Lüdecke",

R/methods_marginaleffects.R

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ model_parameters.marginaleffects <- function(model,
2525
} else {
2626
# handle non-Bayesian models
2727
tidy_model <- marginaleffects::tidy(model, conf_level = ci, ...)
28+
29+
# all columns in data grid and model data, we only want to keep "by" variables
30+
all_data_cols <- union(
31+
colnames(marginaleffects::components(model, "newdata")),
32+
colnames(marginaleffects::components(model, "modeldata"))
33+
)
34+
# columns we want to keep
35+
by_cols <- marginaleffects::components(model, "variable_names_by")
36+
37+
# remove redundant columns
38+
to_remove <- setdiff(all_data_cols, by_cols)
39+
tidy_model <- tidy_model[, !colnames(tidy_model) %in% to_remove, drop = FALSE]
2840
}
2941

3042
out <- .rename_reserved_marginaleffects(tidy_model)

tests/testthat/test-marginaleffects.R

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,31 @@ test_that("marginaleffects()", {
4141
variables = "Petal.Length"
4242
)
4343
expect_identical(nrow(parameters(model)), 1L)
44+
45+
# remove redundant columns
46+
skip_if_not_installed("mgcv")
47+
data(iris)
48+
model <- mgcv::gam(Sepal.Width ~ s(Petal.Length, by = Species), data = iris)
49+
mfx <- marginaleffects::avg_slopes(model, variables = "Petal.Length")
50+
out <- model_parameters(mfx)
51+
expect_identical(dim(out), c(1L, 11L))
52+
expect_named(
53+
out,
54+
c(
55+
"Parameter", "Comparison", "Coefficient", "SE", "Statistic",
56+
"p", "S", "CI", "CI_low", "CI_high", "Predicted"
57+
)
58+
)
59+
mfx <- marginaleffects::avg_slopes(model, variables = "Petal.Length", by = "Species")
60+
out <- model_parameters(mfx)
61+
expect_identical(dim(out), c(3L, 11L))
62+
expect_named(
63+
out,
64+
c(
65+
"Parameter", "Comparison", "Species", "Coefficient", "SE", "Statistic",
66+
"p", "S", "CI", "CI_low", "CI_high"
67+
)
68+
)
4469
})
4570

4671

0 commit comments

Comments
 (0)