How does one transform that pseudo code in R, such that all binding are freezed at the state they were when the function were defined ?
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))
I looked at environments but can't see how to to it properly (nesting environments ?)
You can create and use a new environment with 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
It may also be written with (function(){ ... })()
instead of local
.
instead of `local({ ... })`.
f <- list()
for(i in 1:10) {
f[[i]] <-
(function(){
j <- i
function() j
})()
}
f[[3]]()
Your example becomes:
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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다