Another problem that might cause this is to pass character (string vector ) to lm instead of formula . vector do not have an environment , and therefore, when lm converts character to formula , it apparently also does not have environment instead of automatically assigning a local environment. If you then use the object as a weight, which is not in the data argument of data.frame , but is in the argument of a local function, an not found error appears. This behavior is not very easy to understand. This is probably a mistake.
Here is a minimal reproducible example. This function takes data.frame , two variable names and a weight vector to use.
residualizer = function(data, x, y, wtds) {
And the test:
> residualizer(data = d_example, x = "x", y = "y", wtds = weightsvar) Error in eval(expr, envir, enclos) : object 'wtds' not found > residualizer2(data = d_example, x = "x", y = "y", wtds = weightsvar) 1 2 3 4 5 6 7 8 9 10 0.8986584 -1.1218003 0.6215950 -0.1106144 0.1042559 0.9997725 -1.1634717 0.4540855 -0.4207622 -0.8774290
This is a very subtle mistake. If you go to the function environment using the browser , the weight vector may just be accurate, but it was somehow not found in the lm call!
The error will be more difficult to debug if the name weights was used for the weight variable. In this case, since lm cannot find the weight object, it uses the base weights() function by default, thereby throwing an even stranger error:
Error in model.frame.default(formula = f, data = data, weights = weights, : invalid type (closure) for variable '(weights)'
Do not ask me how many hours it took me to figure this out.