昨天我从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")
}
})
Run Code Online (Sandbox Code Playgroud)
从命令提示符的行为如下:
> 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"
Run Code Online (Sandbox Code Playgroud)
根据1088639中提供的答案,我设置了一对函数,它们都访问相同的子函数环境.这个例子有效,但我想看看我是否错过了将两个顶层函数"连接"到内部环境的更简洁方法.
(背景故事:我想编写一对共享变量的互补函数,例如本例中的"count",并满足CRAN包要求,这些要求不允许函数修改全局环境.)
static.f <- function() {
count <- 0
f <- function(x) {
count <<- count + 1
return( list(mean=mean(x), count=count) )
}
return( f )
}
# make sure not to delete this command, even tho' it's not
# creating a function.
f1 <- static.f()
statfoo <- function(x){
tmp<-f1(x)
tmp<- list(tmp,plus=2)
return(tmp)
}
statbar <- function(x){
tmp<-f1(x)
tmp<- list(tmp,minus=3)
return(tmp)
}
Run Code Online (Sandbox Code Playgroud)
样本输出:
> statfoo(5)
[[1]]
[[1]]$mean
[1] 5
[[1]]$count
[1] 1
$plus
[1] 2
Rgames> …Run Code Online (Sandbox Code Playgroud) 我正在寻找在 R 函数中模拟“静态”变量的方法。(我知道 R 不是编译语言......因此是引号。)对于 'static' 我的意思是 'static' 变量应该是持久的,与函数相关联并且可以从函数内部修改。
我的主要想法是使用该attr功能:
# f.r
f <- function() {
# Initialize static variable.
if (is.null(attr(f, 'static'))) attr(f, 'static') <<- 0L
# Use and/or modify the static variable...
attr(f, 'static') <<- attr(f, 'static') + 1L
# return something...
NULL
}
Run Code Online (Sandbox Code Playgroud)
这很好用,只要attr能找到f。在某些情况下,情况不再如此。例如:
sys.source('f.r', envir = (e <- new.env()))
environment(e$f) <- .GlobalEnv
e$f() # Error in e$f() : object 'f' not found
Run Code Online (Sandbox Code Playgroud)
理想情况下,我会attr在ffrom inside的“指针”上使用 …
我需要求解 的总和(10^2 + 10^3) * 99,总和将为total = (1100+1100+1100...(99 times))。我知道大多数人不喜欢循环,但我需要使用 for 循环来解决这个问题。这是我到目前为止所拥有的......
prob1 <- function(n){
total <- 1100
for(i in 2:99)
total[i] <- sum(i^2 + i^3)
return(total)
}
Run Code Online (Sandbox Code Playgroud)
这就是我得到的
[1] 1100 12 36 80 150 252 392 576 810 1100 1452 1872 2366 2940 3600
[16] 4352 5202 6156 7220 8400 9702 11132 12696 14400 16250 18252 20412 22736 25230 27900
[31] 30752 33792 37026 40460 44100 47952 52022 56316 60840 65600 70602 75852 81356 87120 93150 …Run Code Online (Sandbox Code Playgroud)