[R] Referring to objects themselves

Duncan Murdoch murdoch.duncan at gmail.com
Sun Mar 20 11:43:09 CET 2011


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.

Duncan Murdoch



More information about the R-help mailing list