Re: [R] Referring to objects themselves

From: Kenn Konstabel <lebatsnok_at_gmail.com>
Date: Sun, 20 Mar 2011 15:24:50 +0200

On Sun, Mar 20, 2011 at 12:43 PM, Duncan Murdoch <murdoch.duncan_at_gmail.com>wrote:

> On 11-03-19 10:21 PM, Kenn Konstabel wrote:
>
>> On Sun, Mar 20, 2011 at 4:13 AM, Kenn Konstabel<lebatsnok_at_gmail.com>
>> wrote:
>>
>> you can omit the list and do the following:
>>>
>>>
>>> /.../
>>>
>>> (but you don't really need "this" in this case as you can use "balance"
>>> instead of "this$balance")
>>>
>>>
>> P.S. using "this" would make some difference in one case:
>>
>> instead of
>> total<<- total + amount # need<<- here
>> you can have
>> this$total<- this$total + amount # can use<-
>>
>
> This is a very un-R-like way of programming, so I wouldn't recommend it.
> The reason it works is that environment objects are special: they are
> handled by reference, whereas with most other kinds of objects assignment
> creates a new copy, and assignment with "<-" makes the assignment locally.
>
> So if at some point you switched this to be a list() object instead of an
> environment, the line
>
>
> this$total <- this$total + amount
>
> would have quite a different meaning.
>

I agree that all this is mostly only useful for learning how R works, but then again, the proto package uses something quite similar. Quoting the proto version of open.account from a previous mail:

            .$total <- .$total + amount

The following wouldn't work there:

            total<<-total+amount

As a side dish, it might sometimes be useful to make a function return its environment rather its usual value (if only for the curious people who want to see what is "inside"). The following function does this by just adding environment() as a last line:

strip <-
function(fun.){
# not sure if it's done in the optimal way here

    bf <- body(fun.)
    cb <- quote({})
    cb[[2]] <- bf
    cb[[3]] <- quote(environment())
    body(fun.) <- cb
    fun.
    }

> ls(strip(open.account.2)(100))
[1] "balance" "deposit" "this" "total" "withdraw"

Best regards,

Kenn Konstabel

        [[alternative HTML version deleted]]



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 Sun 20 Mar 2011 - 13:29:00 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 Sun 20 Mar 2011 - 13:30:22 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