[R] Environment question
William Dunlap
wdunlap at tibco.com
Fri Nov 13 19:53:11 CET 2015
Make a new environment for each function and populate it with
the variables that your functions require. local() is a convenient
way to do this:
f.factory3 <- function(destinationEnvir = globalenv())
{
for (y in 2:3) {
fname <- paste("plus", y, sep = ".")
f <- local(function(x) x + y, envir=list2env(list(y=y),
parent=destinationEnvir))
assign(fname, f, envir = destinationEnvir)
}
}
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Nov 13, 2015 at 9:53 AM, ALBERTO VIEIRA FERREIRA MONTEIRO
<albmont at centroin.com.br> wrote:
> I have another environment question.
>
> I understand why this works as expected:
>
> f.factory <- function()
> {
> y <- 2
> fname <- paste("plus", y, sep = ".")
> f <- function(x) x + y
> assign(fname, f, envir = globalenv())
> }
>
> f.factory()
> plus.2(2) # 4
>
> and I also understand why this does NOT work:
>
> f.factory <- function()
> {
> for (y in 2:3) {
> fname <- paste("plus", y, sep = ".")
> f <- function(x) x + y
> assign(fname, f, envir = globalenv())
> }
> }
>
> f.factory()
> plus.2(2) # 5
>
> (the reason is that both plus.2 and plus.3 have the
> same environment as f.factory when f.factory terminates,
> which assign 2 to variable y in the first case and 3 in
> the second case)
>
> However, I don't know an elegant way to adapt f.factory
> so that it works as expected. Any suggestions?
>
> Alberto Monteiro
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list