I'm writing a function that requires a weighted regression. I've repeatedly been getting an error with the weights parameter, and I've created a minimal reproducible example you can find here:
wt_reg <- function(form, data, wts) {
lm(formula = as.formula(form), data = data,
weights = wts)
}
wt_reg(mpg ~ cyl, data = mtcars, wts = 1:nrow(mtcars))
This returns
Error in eval(extras, data, env) : object 'wts' not found
If you run this all separately, it works fine. I've dug into lm, and it appears the issue is a call to eval(mf, parent.frame())
. Even though wts is in the parent.frame(), it doesn't appear to be evaluated correctly within the call. Here's a little more detail:
mf is assigned such that it's the same as
stats::model.frame(formula = as.formula(form), data = data, weights = wts,
drop.unused.levels = TRUE)
When I run
parent.frame()$wts
it does return a numeric vector. But when I run
eval(stats::model.frame(formula = as.formula(form), data = data, weights = wts,
drop.unused.levels = TRUE), parent.frame())
it doesn't.
I can run
stats::model.frame(formula = as.formula(parent.frame()$form),
data = parent.frame()$data, weights = parent.frame()$wts,
drop.unused.levels = TRUE)
and it works. You can test this yourself if you want using the example from the top.
Any thoughts? I really have no idea what's going on here...