[R] Help with first S3-class

Martin Møller Skarbiniks Pedersen traxplayer at gmail.com
Wed Jan 3 00:38:32 CET 2018


Hi,

  I am trying to understand S3 classes. I have read several tutorials about
the topics but I am still a bit confused. I guess it is because it is
so different from
Java OOP.

  I have pasted my attempt at creating a bank-account class below and
my problems are:

1. What should be added some plot.default() calls the account$plot() method ?
2. What should the account$plot() be implemented to show some kind of plot ?
3. How can one function inside "me"-list called another function. Eg.
How can account$plot() call account$pastSaldo() ?

Here are my code. Feel free to comment on any aspect of the code.
ps. I hope I have manage to strip HTML.

Regards
Martin



account <- function(owner = NULL) {
    thisEnv <- environment()

    pastSaldo <- vector()
    saldo <- 0
    owner <- owner

    me <- list(
    thisEnv = thisEnv,

         getEnv = function() { return(get("thisEnv", thisEnv)) },

         balance = function() { return(get("saldo", thisEnv)) },

        deposit = function(value) {
            assign("pastSaldo", append(pastSaldo, saldo), thisEnv)
            assign("saldo", saldo + value, thisEnv)
        },

        withdraw = function(value) {
           assign("pastSaldo", append(pastSaldo, saldo), thisEnv)
           assign("saldo", saldo - value, thisEnv)
        },

       pastSaldo = function() {
          return(pastSaldo)
      },

      plot = function() {
         plot.new()
         lines(list(y = pastSaldo, x = seq_along(pastSaldo)))
       }
    )
    assign('this', me, envir = thisEnv)

    class(me) <- append(class(me), "account")
    return(me)
}

FirstAccount <- account("Martin")
FirstAccount$deposit(100)
FirstAccount$withdraw(50)
FirstAccount$deposit(200)
FirstAccount$balance()
FirstAccount$pastSaldo()

FirstAccount$plot()

plot(FirstAccount)                            # fails
plot.account(FirstAccount)               # fails



More information about the R-help mailing list