Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: function passed as argument is not found

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
like image 279
linuxfever Avatar asked Aug 22 '13 14:08

linuxfever


1 Answers

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
}
like image 183
Dason Avatar answered Sep 27 '22 17:09

Dason