昨天我从Bill Venables那里学到了local()如何帮助创建静态函数和变量,例如:
example <- local({
hidden.x <- "You can't see me!"
hidden.fn <- function(){
cat("\"hidden.fn()\"")
}
function(){
cat("You can see and call example()\n")
cat("but you can't see hidden.x\n")
cat("and you can't call ")
hidden.fn()
cat("\n")
}
})
该命令在命令提示符下的行为如下:
> ls()
[1] "example"
> example()
You can see and call example()
but you can't see hidden.x
and you can't call "hidden.fn()"
> hidden.x
Error: object 'hidden.x' not found
> hidden.fn()
Error: could not find function "hidden.fn"
我在R中的静态变量讨论中看到过这种情况,并采用了不同的方法。这两种方法各有优缺点,请问您觉得哪个更好呢?
local
让记忆化(memoization)更加方便。在"The R Inferno"中有一个例子。 - otsaw