[R] Referring to objects themselves

Gabor Grothendieck ggrothendieck at gmail.com
Sun Mar 20 02:06:11 CET 2011


On Sat, Mar 19, 2011 at 8:02 PM, Russ Abbott <russ.abbott at gmail.com> wrote:
> Actually, I guess I'm not really talking about objects. I was looking
> through the scoping demo. It uses this function.
>
>> open.account <- function(total) {
>
> +
>
> +     list(
>
> +        deposit = function(amount) {
>
> +            if(amount <= 0)
>
> +                stop("Deposits must be positive!\n")
>
> +            total <<- total + amount
>
> +            cat(amount,"deposited. Your balance is", total, "\n\n")
>
> +        },
>
> +        withdraw = function(amount) {
>
> +            if(amount > total)
>
> +                stop("You don't have that much money!\n")
>
> +            total <<- total - amount
>
> +            cat(amount,"withdrawn.  Your balance is", total, "\n\n")
>
> +        },
>
> +        balance = function() {
>
> +            cat("Your balance is", total, "\n\n")
>
> +        }
>
> +        )
>
> + }
>
> I wanted to re-write the function so that instead of referring to total in
> deposit and withdraw I could refer to balance. Something like this,
>
> withdraw = function(amount) {
> +            if(amount > total)
> +                stop("You don't have that much money!\n")
> +            total <<- total - amount
> +            cat(amount,"withdrawn.  Your balance is", this,balance(),
> "\n\n")
>
> But that doesn't work. Is it possible to do this?
> Thanks.
>

Try this:

open.account <- function(total) {
    this <- environment()
    list(...same list as before...)
}

Now within the body of any of the methods in the list, this$total
refers to the balance.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list