-1

関数が定義されたときの状態ですべてのバインディングが凍結されるように、R でその疑似コードをどのように変換しますか?

lastfunction <- function(inputx) {rep(0,length(inputx))}
i<-1
while(i<=2){
  afunction <- function(inputx) {i*inputx} #freeze all variable used in the body
  lastfunction <- lastfunction + afunction #and of course the label "afunction" as well
  i<-i+1
}

#then apply to some data
lastfunction(c(0,1,5,6))

私は環境を見ましたが、それを適切に行う方法がわかりません(ネスト環境?)

4

1 に答える 1

2

で新しい環境を作成して使用できますlocal

f <- list()
for(i in 1:10) {
  f[[i]] <- local({
      j <- i  # j is only visible in this local environment, 
              # and it is a different environment at each iteration.
      function() j
  })
}
f[[3]]()
# [1] 3

(function(){ ... })()の代わりにと書くこともありますlocal

instead of `local({ ... })`.
f <- list()
for(i in 1:10) {
  f[[i]] <- 
    (function(){
      j <- i
      function() j
    })()
}
f[[3]]()

あなたの例は次のようになります。

f <- function(x) rep(0, length(x))
for(i in -1:2) {
  f <- local({
    # Copy the variables i and f 
    j  <- i
    g1 <- f
    g2 <- function(x) j*x
    # Define the new function
    function(x) {
      cat( "i=", j, " Adding ", paste0(g2(x),sep=","), "\n", sep="" )
      g1(x) + g2(x)
    }
  })
}

# Check that result is correct
h <- function(x) 2*x
f(1:3)
# i=2 Adding 2,4,6,
# i=1 Adding 1,2,3,
# i=0 Adding 0,0,0,
# i=-1 Adding -1,-2,-3,
# [1] 2 4 6
h(1:3)
# [1] 2 4 6
于 2013-08-11T07:57:59.583 に答える