[R] Environment question

ALBERTO VIEIRA FERREIRA MONTEIRO albmont at centroin.com.br
Fri Nov 13 18:53:29 CET 2015


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



More information about the R-help mailing list