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
The issue comes up with how lm looks for the data. If you change the function to this 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With