Error in BAS:::coef.bas(..., estimator = "MPM"): Error in eval(object$call$weights): object 'object' not found
vandenman opened this issue · 1 comments
Describe the bug
Calling BAS:::coef.bas(basobj, estimator = "MPM")
may error depending on how basobj
was created.
To Reproduce
The first example works as intended. The second example changes the seemingly harmless formula = M ~ So + Ed + Po1 + Po2
into formula = form
where form
is defined earlier form = M ~ So + Ed + Po1 + Po2
.
data(UScrime, package = "MASS")
UScrime <- UScrime[, 1:5]
crime.bic <- BAS::bas.lm(
formula = M ~ So + Ed + Po1 + Po2,
data = UScrime,
prior = "JZS",
initprobs = c(1, 0.5, 0.5, 0.5, 0.5),
renormalize = TRUE
)
BAS:::coef.bas(crime.bic, estimator = "MPM")
#>
#> Marginal Posterior Summaries of Coefficients:
#>
#> Using MPM
#>
#> Based on the top 1 models
#> post mean post SD post p(B != 0)
#> Intercept 138.57447 1.40051 1.00000
#> So 11.53684 3.13294 1.00000
#> Ed 0.00000 0.00000 0.00000
#> Po1 0.00000 0.00000 0.00000
#> Po2 -0.14815 0.05367 1.00000
form <- M ~ So + Ed + Po1 + Po2
crime.bic2 <- BAS::bas.lm(
formula = form,
data = UScrime,
prior = "JZS",
initprobs = c(1, 0.5, 0.5, 0.5, 0.5),
renormalize = TRUE
)
BAS:::coef.bas(crime.bic2, estimator = "MPM")
#> Error in eval(object$call$weights): object 'object' not found
Created on 2022-02-02 by the reprex package (v2.0.1)
What goes wrong, is that this code
Lines 87 to 99 in f92fc3e
is doing things with eval
. However, since R is lazy, the evals are not evaluated until we get to
Line 514 in f92fc3e
where R tries to do eval(expression(stats::model.frame(formula = eval(object$call$formula), data = eval(object$call$data), weights = eval(object$call$weights), drop.unused.levels = TRUE)), parent.frame())
but this fails. I don't really understand why this fails though, as env <- parent.frame(); env$object
during debugging does return the objects that R cannot find.
Expected behavior
The same output as in the first version.
Desktop:
- OS: Ubuntu 20.04
- R Version 4.1.2
Thank you for the very detailed reproducible example. Issue was with the formula environment as discussed in
StackOverflow https://stackoverflow.com/questions/61164404/call-to-weight-in-lm-within-function-doesnt-evaluate-properly/61164660#61164660?newreg=04a2b71c6da04693a5b172a54a4a43b0
which was key to solving!
Please let me know if there any remaining issues that crop up - m