lin*_*ver 8 iteration regression r function
我试图在R中编写一个简单的迭代重加权最小二乘算法.我想传递一个函数作为计算权重的参数,但遗憾的是R抱怨该函数无法找到.我有什么想法我做错了吗?提前致谢!
这是我的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
和一个愚蠢的例子来证明这个问题
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
Run Code Online (Sandbox Code Playgroud)
问题出现了lm如何查找数据.如果您将功能更改为此功能似乎可以正常工作
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
}
Run Code Online (Sandbox Code Playgroud)
在formula包含初始的环境中lm调用(.GlobalEnv在这种情况下),其中wfunc不可用.作为解决方法,您可以将其替换为当前环境.
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)
Run Code Online (Sandbox Code Playgroud)