Re: [R] best practice(s) for retrieving a local variable from a closure

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sat, 09 Apr 2011 15:40:19 -0400

On Sat, Apr 9, 2011 at 3:27 PM, Barry Rowlingson <b.rowlingson_at_lancaster.ac.uk> wrote:
> On Sat, Apr 9, 2011 at 6:29 PM, Benjamin Tyner <btyner@gmail.com> wrote:
>
>>> The above feels a bit like snooping where I wasn't invited.
>>> You could do something like
>>>  mq <- function(a) {
>>>     force(a)
>>>     list(getA = function()a,
>>>          setA = function(newA) a <<- newA,
>>>          fun = function(x)x^a
>>>     )
>>>  }
>>> to make it clear that you expect people to look at or change
>>> fun's 'a'.
>
>  Once you start doing a lot of that though you may as well go the
> whole OO hog and use the proto or R.oo packages...
>
> Barry
>

In the case of proto it would be this:

library(proto)
mq <- proto(fun = function(., x) x^.$a)

mq$a <- 2
mq$a # 2
mq$fun(3) # 9

or you could make explicit getter and setter functions though, as seen, they are not really needed:

mq <- proto(fun = function(., x) x^.$a,

		getA = function(.) .$a,
		setA = function(., a) .$a <- a)

mq$setA(3)

mq$getA() # 3
mq$fun(4) # 64
-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

______________________________________________
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.
Received on Sat 09 Apr 2011 - 19:44:20 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 09 Apr 2011 - 19:50:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive