Re: [R] Referring to objects themselves

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sat, 19 Mar 2011 23:29:00 -0400

On Sat, Mar 19, 2011 at 9:45 PM, Russ Abbott <russ.abbott_at_gmail.com> wrote:
> Thanks for all the suggestions. I realize that this isn't the most important
> thing in the world -- and as a newcomer to R I gather it's not the way most
> people use R anyway.
>
> But I tried to do what looked like the simplest suggestion.
>
> open.account.2 <- function(total) {
>       this <- environment()
>       list(
>         deposit = function(amount) {
>           if(amount <= 0)
>             stop("Deposits must be positive!\n")
>           total <<- total + amount
>           cat(amount, "deposited.  Your balance is", this$balance(),
> "\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", this$balance(),
> "\n\n")
>         },
>         balance = function() {
>           cat("Your balance is", this$total, "\n\n")
>         }
>       )
>     }
>
> When I ran it, this is what happened.
>
>> x <- open.account.2(100)
>> x$balance()
>
> Your balance is 100
>
> OK so far. But
>
>> x$deposit(50)
> Error in cat(amount, "deposited.  Your balance is", this$balance(), "\n\n")
> :
>  attempt to apply non-function
>
>
> Am I doing this the wrong way?
>
> Thanks for your interest.
>

balance is a component of the list. Its not directly a component of this. If you name the list you can refer to it as this$methods$balance

open.account.2 <- function(total) {
       this <- environment()
       methods <- list(...whatever...)
 }

-- 
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 Sun 20 Mar 2011 - 03:32:22 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 - 04:00:23 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