[R] How to use current value of variable in function definition?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jul 3 02:10:22 CEST 2009


The proto package generalizes this to an OO approach based
on the prototype or object-based model of OO.

This corresponds to the previous code:

library(proto)
p <- proto(c = 1, foo = function(.) print(.$c))
p$foo() # 1

# but now we can also create q which overrides c
# while inheriting foo from p

q <- p$proto(c = 2)
q$foo() # 2

Here

On Thu, Jul 2, 2009 at 4:35 PM, Peter Dalgaard<p.dalgaard at biostat.ku.dk> wrote:
> Mark Wardle wrote:
>>
>> Hi.
>>
>> I've stared at your code for a number of minutes and can't understand
>> what you're trying to achieve here. It looks as if you're fighting
>> scope - it may be worth refactoring your approach to simplify matters.
>> Otherwise, it sounds like a recipe for obfuscation! What are you
>> trying to do really?
>
> Not really obfuscation, there are legitimate reasons to want this sort of
> behaviour. See demo(scoping) for a related example
>
> I think the canonical way is to define the function in an environment that
> contains c
>
> foo <- local({c <- 1 ; function() print(c) })
>
> which really isn't much different from what his "painful" code is doing.
>
>> b/w
>>
>> Mark
>>
>> 2009/7/2 Allan Engelhardt <allane at cybaea.com>:
>>>
>>> Must be the heat or something but I can't get my brain into gear and
>>> figure
>>> out how to get something like
>>>
>>> if (1) { c <- 1; foo <- function () print(c); }
>>> c <- 2
>>> foo()
>>>
>>> to print 1, not 2.  (The real life example is a little more complex, but
>>> you
>>> get the idea.  I don't want the variable c in the function definition, I
>>> want its value at that time.)
>>>
>>> The only thing I have been able to come up with is something like
>>>
>>> if (1) foo <- (function () { c <- 1; return(function () print(c)) })()
>>> c <- 2
>>> foo()
>>> # [1] 1
>>>
>>> but that just hurts.  Please make the pain go away.
>>>
>>> Can someone wake up my brain?
>>>
>>> Allan.
>>>
>>> ______________________________________________
>>> 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.
>>>
>>>
>>
>>
>>
>
>
> --
>   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
>  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
>  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907
>
> ______________________________________________
> 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