2016-03-23 86 views
0

我試圖varable表達傳遞給lazyeval函數的參數:參數爲懶惰的評價

test <- function(expr){ 
    tmp <- iris[eval(substitute(expr), iris), ] 
    #actually do and return complicated stuff with tmp 
    return(data.frame(n = nrow(tmp), sepal.length = mean(tmp$Sepal.Length))) 
} 

test.species <- function(species){ 
    return(test(Species == substitute(species))) 
} 

#usage: 
test.species("virginica") 

功能測試工作得很好。但爲什麼test.species不工作?

回答

1

substitute(Species == substitute(species))test的內部進行評估,這意味着Species不會與字符值進行比較,而會與符號(substitute(species))進行比較。

bquote可以在這裏而不是使用:

test.species <- function(species){ 
    eval(bquote(test(Species == .(species)))) 
} 
test.species("virginica") 
# n sepal.length 
#1 50  6.588 
+0

謝謝!這工作完美。正如我剛剛發現的那樣,eval(替代品(Species ==。(species)))也會起作用。 bquote和替代品在這裏有什麼區別嗎? –

+0

請記住,非標準的評估可以很好,但通常更好地堅持標準評估(例如,更容易調試)。 – Roland

+0

@恆瑞江你把那個放在哪裏?它不應該工作。 – Roland