我想在R中編寫一個簡單的迭代重新加權最小二乘算法。我想傳遞一個函數作爲權重計算的參數,但不幸的是,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
}
和一個愚蠢的例子來說明這個問題
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
奇怪。看來問題出現在'lm'中。當它試圖找到以下行中的函數:'mf < - eval(mf,parent.frame())' – nograpes
它可能有所幫助:http://stackoverflow.com/questions/7027288/error-could-not- find-function-in-r – Fernando
我認爲你最好先定義你的函數。 ''wfunc <-function(x){rep(1,length(x $ fit))}'後跟'irls(mlm,wfunc,0.001)' –