R: function passed as argument not found

I am trying to write a simple iterative zero-square least-square algorithm in R. I want to pass a function as an argument to calculate the weights, but unfortunately R complains that the function cannot be found. Any ideas what I'm doing wrong? Thanks in advance!

Here is my code:

irls <- function(imodel, wfunc, tol) { repeat { b0 <- imodel$coef imodel <- lm(formula(imodel), weights=wfunc(imodel), data=imodel$model) b1 <- imodel$coef if(abs((b1-b0)/b0)<=tol) break } imodel } 

and stupid example to demonstrate the problem

 x <- 1:100 y <- x + rnorm(100) mlm <- lm(y~x-1) irls(mlm, function(x){rep(1,length(x$fit))},0.001) # error: wfunc not found 
+8
function iteration r regression
source share
3 answers

The problem is how lm searches for data. If you change the function to it, it seems to work

 irls <- function(imodel, wfunc, tol) { repeat { b0 <- imodel$coef dat <- imodel$model dat$wts <- wfunc(imodel) imodel <- lm(formula(imodel), weights=wts, data=dat) b1 <- imodel$coef if(abs((b1-b0)/b0)<=tol) break } imodel } 
+8
source share

formula contains the lm initial call environment ( .GlobalEnv , in this case), in which wfunc not available. As a workaround, you can replace it with the current environment.

 irls <- function(imodel, wfunc, tol) { f <- formula(imodel) environment(f) <- environment() repeat { b0 <- imodel$coef imodel <- lm(f, weights=wfunc(imodel), data=imodel$model) b1 <- imodel$coef if(abs((b1-b0)/b0)<=tol) break } imodel } irls(mlm, function(x){rep(1,length(x$fit))},0.001) 
+5
source share

This problem arises because model.frame.default is called inside lm , which evaluates everything in the environment of the formula:

 model.frame.default #function (formula, data = NULL, subset = NULL, na.action = na.fail, # drop.unused.levels = FALSE, xlev = NULL, ...) #{ #... # env <- environment(formula) #... # extras <- eval(extras, data, env) <-- this is where you run into a problem #... 

Since others have suggested, evaluate the function outside of lm .

-one
source share

All Articles