2015-06-02 49 views
2

嗨,我試着準備一個關於R中的閉包的小代碼,當時我偶然發現了一些奇怪的行爲。使用調試我意識到發生了故障,由於這樣的事實,LM內正在執行這一行R中的關閉和lm

mf <- eval(mf, parent.frame()) 

但它似乎擊敗帶密封蓋的編程功能方面?

我失蹤了什麼?這裏是我的小例子EVAL

# typical closure use 
foo <- function(formula,data,weight=NULL) { 
    if(is.null(weight)) w=ones(nrow(data),1) else w=weight  
    force(w) 
    lm(formula,data,weights=w) 
} 

setup_something <- function(...) { 
    function(formula,data) { 
    foo(formula,data,...) 
    } 
} 

# set up our model function 
model <- setup_something() 

# set up our data 
df = data.frame(x=seq(1,10,1),y=c(1:10)^1.5 * 3 + 2) 
model(y~x,df) 

錯誤(表達式,ENVIR,enclos):對象 'W' 未找到

+0

它可能會有幫助:[範圍界定問題](http://adv-r.had.co.nz/Computing-on-the-language.html#scoping-issues) – zero323

回答

1

實例化一個公式(即x~y)同時捕捉它是環境創建於,您的案例發生在您致電model()parent.frame()中。通過更換您的來電lm(formula,data,weights=w)

# explicitly replace the formula's environment with the current frame 
attr(formula,'.Environment') <- sys.frame(sys.nframe()) 
通過

或含蓄:

#instantiate a new forumla based on the existing formula 
lm(stats::formula(unclass(formula)),data,weights=w) 

如果你想征服的環境中,你可以通過加入這一行呼叫之前,有權lm(formula,data,weights=w)明確地這樣做

這種背景下,如果你要堅持以下行lm()調用mf <- eval(mf, parent.frame())前右:

print(ls(envir=parent.frame())) 

您將得到包含"w"的對象名稱列表。然而,被評估的「MF」對象是stats::model.frame由於這一行:

mf[[1L]] <- quote(stats::model.frame) 

stats::model.frame評估參數mf在式.Environment屬性的上下文。

+0

非常感謝,這是一個很好的解釋我確實錯過了公式也捕捉到了一個環境的事實。 thx b :) – bernddude