I am trying to write a simple iterative reweighted least squares algorithm in R. I want to pass a function as argument for the calculation of the weights, but unfortunately R complains that the function cannot be found. Any ideas what I am 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 a silly 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