[R] Putting an index explicitly into function code --- a curiosity.

William Dunlap wdunlap at tibco.com
Sun Jan 8 20:29:14 CET 2012


The following gives a list, 'z', of functions with
different values of the variable 'i':
  > z <- lapply(1:3, function(i) { force(i) ; function() cat("i is", i, "\n")})
  > z[[3]]()
  i is 3 
  > z[[2]]()
  i is 2
Their printed values don't show the difference,
as they depend on the 'i' stored in their environments:
  > z
  [[1]]
  function () 
  cat("i is", i, "\n")
  <environment: 0x0422c574>

  [[2]]
  function () 
  cat("i is", i, "\n")
  <environment: 0x0422b97c>

  [[3]]
  function () 
  cat("i is", i, "\n")
  <environment: 0x0422bb04>
You can look at their environments with
  > lapply(z, function(zi)ls.str(environment(zi)))
  [[1]]
  i :  int 1

  [[2]]
  i :  int 2
  
  [[3]]
  i :  int 3

These environments will survive a save/load cycle but will
silently disappear in a dump/source cycle.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Rolf Turner
> Sent: Saturday, January 07, 2012 2:07 PM
> To: Carl Witthoft
> Cc: r-help at r-project.org
> Subject: Re: [R] Putting an index explicitly into function code --- a curiosity.
> 
> On 08/01/12 05:24, Carl Witthoft wrote:
> > Now that we've all satisfied our curiosity :-)  about force() in for
> > and while loops,  I suppose it would be impolite to ask Rolf whether
> > there isn't a much neater and simpler way to make his internal
> > functions grab whatever the index 'i' is pointing them to?
> 
> No.  There isn't.  I need what I said I needed:  a list of functions,
> the i-th function in the list explicitly involving the index "i".
> 
>      cheers,
> 
>          Rolf Turner
> 
> ______________________________________________
> R-help at r-project.org mailing list
> 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