SlideShare a Scribd company logo
Object Oriented Design(s) in R




                  Romain François
              romain@r-enthusiasts.com


Chicago Local R User Group, Oct 27th , Chicago.
Outline




          Lexical Scoping
          S3 classes
          S4 classes
          Reference (R5) classes
          C++ classes
          Protocol Buffers
Fil rouge: bank account example

                       Data:
                        - The balance
                        - Authorized overdraft




                       Operations:
                        -   Open an account
                        -   Get the balance
                        -   Deposit
                        -   Withdraw
                   .
Lexical Scoping
> open.account <- function(total, overdraft = 0.0){
+     deposit <- function(amount) {
+         if( amount < 0 )
+             stop( "deposits must be positive" )
+         total <<- total + amount
+     }
+     withdraw <- function(amount) {
+         if( amount < 0 )
+             stop( "withdrawals must be positive" )
+         if( total - amount < overdraft )
+             stop( "you cannot withdraw that much" )
+         total <<- total - amount
+     }
+     balance <- function() {
+         total
+     }
+     list( deposit = deposit, withdraw = withdraw,
+         balance = balance )
+ }
> romain <- open.account(500)
> romain$balance()
[1] 500

> romain$deposit(100)
> romain$withdraw(200)
> romain$balance()
[1] 400
S3 classes
S3 classes


      Any R object with a class attribute
      Very easy
      Very dangerous
      Behaviour is added through S3 generic functions

  > Account <- function( total, overdraft = 0.0 ){
  +     out <- list( balance = total, overdraft = overdraft )
  +     class( out ) <- "Account"
  +     out
  + }
  > balance <- function(x){
  +     UseMethod( "balance" )
  + }
  > balance.Account <- function(x) x$balance
S3 classes

  > deposit <- function(x, amount){
  +     UseMethod( "deposit" )
  + }
  > deposit.Account <- function(x, amount) {
  +     if( amount < 0 )
  +         stop( "deposits must be positive" )
  +     x$balance <- x$balance + amount
  +     x
  + }
  > withdraw <- function(x, amount){
  +     UseMethod( "withdraw" )
  + }
  > withdraw.Account <- function(x, amount) {
  +     if( amount < 0 )
  +         stop( "withdrawals must be positive" )
  +     if( x$balance - amount < x$overdraft )
  +         stop( "you cannot withdraw that much" )
  +     x$balance <- x$balance - amount
  +     x
  + }
S3 classes




  Example use:
  > romain <- Account( 500 )
  > balance( romain )
  [1] 500

  > romain <- deposit( romain, 100 )
  > romain <- withdraw( romain, 200 )
  > balance( romain )
  [1] 400
S4 classes
S4 classes




     Formal class definition
     Validity checking
     Formal generic functions and methods
     Very verbose, both in code and documentation
S4 classes
  > setClass( "Account",
  +     representation(
  +         balance = "numeric",
  +         overdraft = "numeric"
  +     ),
  +     prototype = prototype(
  +         balance = 0.0,
  +         overdraft = 0.0
  +     ),
  +     validity = function(object){
  +         object@balance > object@overdraft
  +     }
  + )
  [1] "Account"

  > setGeneric( "balance",
  +     function(x) standardGeneric( "balance" )
  + )
  [1] "balance"

  > setMethod( "balance", "Account",
  +     function(x) x@balance
  + )
  [1] "balance"
S4 classes



  > setGeneric( "deposit",
  +     function(x, amount) standardGeneric( "deposit" )
  + )
  [1] "deposit"

  > setMethod( "deposit",
  +     signature( x = "Account", amount = "numeric" ),
  +     function(x, amount){
  +         new( "Account" ,
  +             balance = x@balance + amount,
  +             overdraft = x@overdraft
  +         )
  +     }
  + )
  [1] "deposit"
S4 classes




  > romain <- new( "Account", balance = 500 )
  > balance( romain )
  [1] 500

  > romain <- deposit( romain, 100 )
  > romain <- withdraw( romain, 200 )
  > balance( romain )
  [1] 400
Reference (R5) classes
Reference (R5) classes




     Real S4 classes: formalism, dispatch, ...
     Passed by Reference
     Easy to use
Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers


       > Account <- setRefClass( "Account_R5",
       +     fields = list(
       +         balance = "numeric",
       +         overdraft = "numeric"
       +     ),
       +     methods = list(
       +         withdraw = function( amount ){
       +             if( amount < 0 )
       +                 stop( "withdrawal must be positive" )
       +             if( balance - amount < overdraft )
       +                 stop( "overdrawn" )
       +             balance <<- balance - amount
       +         },
       +         deposit = function(amount){
       +             if( amount < 0 )
       +                 stop( "deposits must be positive" )
       +             balance <<- balance + amount
       +         }
       +     )
       + )
       > x <- Account$new( balance = 10.0, overdraft = 0.0 )
       > x$withdraw( 5 )
       > x$deposit( 10 )
       > x$balance
       [1] 15
                                        Romain François      Objects @ Chiacgo R User Group/Oct 2010
Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers




      Real pass by reference :
       > borrow <- function( x, y, amount = 0.0 ){
       +     x$withdraw( amount )
       +     y$deposit( amount )
       +     invisible(NULL)
       + }
       > romain <- Account$new( balance = 5000, overdraft = 0.0 )
       > dirk <- Account$new( balance = 3, overdraft = 0.0 )
       > borrow( romain, dirk, 2000 )
       > romain$balance
       [1] 3000

       > dirk$balance
       [1] 2003




                                        Romain François      Objects @ Chiacgo R User Group/Oct 2010
Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers




      Adding a method dynamically to a class :
       > Account$methods(
       +     borrow = function(other, amount){
       +         deposit( amount )
       +         other$withdraw( amount )
       +         invisible(NULL)
       +     }
       + )
       > romain <- Account$new( balance = 5000, overdraft = 0.0 )
       > dirk <- Account$new( balance = 3, overdraft = 0.0 )
       > dirk$borrow( romain, 2000 )
       > romain$balance
       [1] 3000

       > dirk$balance
       [1] 2003




                                        Romain François      Objects @ Chiacgo R User Group/Oct 2010
C++ classes
C++ classes

  class Account {
  public:
       Account() :   balance(0.0), overdraft(0.0){}

      void withdraw( double amount ){
          if( balance - amount < overdraft )
               throw std::range_error( "no way") ;
          balance -= amount ;
      }

      void deposit( double amount ){
          balance += amount ;
      }

      double balance ;

  private:
       double overdraft ;
  } ;
C++ classes

  Exposing to R through Rcpp modules:
  RCPP_MODULE(yada){
      class_<Account>( "Account")

          // expose the field
          .field_readonly( "balance", &Account::balance )

          // expose the methods
          .method( "withdraw", &Account::withdraw )
          .method( "deposit", &Account::deposit ) ;

  }

  Use it in R:
  > Account <- yada$Account
  > romain <- Account$new()
  > romain$deposit( 10 )
  > romain$withdraw( 2 )
  > romain$balance
  [1] 8
Protocol Buffers
Protocol Buffers

  Define the message type, in Account.proto :
   package foo ;

   message Account {
       required double balance = 1 ;
       required double overdraft = 2 ;
   }



  Load it into R with RProtoBuf:
   > require( RProtoBuf )
   > loadProtoFile( "Account.proto"   )


  Use it:
  > romain <-    new( foo.Account,
   +       balance = 500, overdraft = 10 )
   >   romain$balance
Questions ?




           Romain François
 http://romainfrancois.blog.free.fr
      romain@r-enthusiasts.com

Chicago Local R User Group, Oct 27th , Chicago.

More Related Content

PDF
Java Se next Generetion
PDF
The Ring programming language version 1.2 book - Part 19 of 84
PDF
A bit about Scala
PDF
The Ring programming language version 1.6 book - Part 39 of 189
PPTX
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
PDF
The Ring programming language version 1.10 book - Part 47 of 212
PDF
The Ring programming language version 1.8 book - Part 35 of 202
KEY
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
Java Se next Generetion
The Ring programming language version 1.2 book - Part 19 of 84
A bit about Scala
The Ring programming language version 1.6 book - Part 39 of 189
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.8 book - Part 35 of 202
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB

What's hot (20)

PDF
The Ring programming language version 1.9 book - Part 38 of 210
PDF
The Ring programming language version 1.5.1 book - Part 43 of 180
PDF
The Ring programming language version 1.5.4 book - Part 30 of 185
KEY
CS442 - Rogue: A Scala DSL for MongoDB
PDF
The Ring programming language version 1.3 book - Part 28 of 88
PDF
Polynomial
PDF
The Ring programming language version 1.2 book - Part 23 of 84
PPT
Xm lparsers
PDF
RESTful API using scalaz (3)
PDF
Seductions of Scala
PDF
The Ring programming language version 1.4.1 book - Part 13 of 31
PDF
2013 - Benjamin Eberlei - Doctrine 2
PDF
The Ring programming language version 1.3 book - Part 21 of 88
PDF
The Ring programming language version 1.5.3 book - Part 37 of 184
PPTX
Groovy vs Boilerplate and Ceremony Code
ODP
JavaScript Web Development
PDF
Java and j2ee_lab-manual
PDF
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
PPTX
Legacy lambda code
PPT
Streams and lambdas the good, the bad and the ugly
The Ring programming language version 1.9 book - Part 38 of 210
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.4 book - Part 30 of 185
CS442 - Rogue: A Scala DSL for MongoDB
The Ring programming language version 1.3 book - Part 28 of 88
Polynomial
The Ring programming language version 1.2 book - Part 23 of 84
Xm lparsers
RESTful API using scalaz (3)
Seductions of Scala
The Ring programming language version 1.4.1 book - Part 13 of 31
2013 - Benjamin Eberlei - Doctrine 2
The Ring programming language version 1.3 book - Part 21 of 88
The Ring programming language version 1.5.3 book - Part 37 of 184
Groovy vs Boilerplate and Ceremony Code
JavaScript Web Development
Java and j2ee_lab-manual
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Legacy lambda code
Streams and lambdas the good, the bad and the ugly
Ad

Similar to Object Oriented Design(s) in R (20)

PDF
Scala by Luc Duponcheel
PDF
Refactoring to Macros with Clojure
PDF
Functional Principles for OO Developers
PDF
Clojure functions examples
PPTX
Smarter Testing With Spock
PPTX
C++ process new
PDF
The Future Shape of Ruby Objects
PDF
ActiveRecord Query Interface (2), Season 2
PDF
Clean Architecture Applications in Python
PDF
Improving application design with a rich domain model (springone 2007)
PDF
用Tornado开发RESTful API运用
KEY
More to RoC weibo
PDF
Android DevConference - Android Clean Architecture
DOCX
exportDisabledUsersRemoveMailbox
PDF
R tutorial (R program 101)
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PPTX
Pellucid stm
PPTX
Presentation on C++ Programming Language
PDF
Apache Spark for Library Developers with William Benton and Erik Erlandson
PDF
Compose Async with RxJS
Scala by Luc Duponcheel
Refactoring to Macros with Clojure
Functional Principles for OO Developers
Clojure functions examples
Smarter Testing With Spock
C++ process new
The Future Shape of Ruby Objects
ActiveRecord Query Interface (2), Season 2
Clean Architecture Applications in Python
Improving application design with a rich domain model (springone 2007)
用Tornado开发RESTful API运用
More to RoC weibo
Android DevConference - Android Clean Architecture
exportDisabledUsersRemoveMailbox
R tutorial (R program 101)
The Ring programming language version 1.7 book - Part 48 of 196
Pellucid stm
Presentation on C++ Programming Language
Apache Spark for Library Developers with William Benton and Erik Erlandson
Compose Async with RxJS
Ad

More from Romain Francois (20)

PDF
PDF
dplyr and torrents from cpasbien
PDF
dplyr use case
PDF
PDF
user2015 keynote talk
PDF
SevillaR meetup: dplyr and magrittr
PDF
PDF
Data manipulation with dplyr
PDF
R/C++ talk at earl 2014
PDF
Rcpp11 genentech
PDF
Rcpp11 useR2014
PDF
PDF
R and C++
PDF
R and cpp
PDF
Rcpp attributes
PDF
Rcpp is-ready
PDF
Integrating R with C++: Rcpp, RInside and RProtoBuf
PDF
Rcpp: Seemless R and C++
PDF
RProtoBuf: protocol buffers for R
dplyr and torrents from cpasbien
dplyr use case
user2015 keynote talk
SevillaR meetup: dplyr and magrittr
Data manipulation with dplyr
R/C++ talk at earl 2014
Rcpp11 genentech
Rcpp11 useR2014
R and C++
R and cpp
Rcpp attributes
Rcpp is-ready
Integrating R with C++: Rcpp, RInside and RProtoBuf
Rcpp: Seemless R and C++
RProtoBuf: protocol buffers for R

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Encapsulation theory and applications.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Electronic commerce courselecture one. Pdf
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
MYSQL Presentation for SQL database connectivity
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation theory and applications.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Programs and apps: productivity, graphics, security and other tools
Electronic commerce courselecture one. Pdf
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Dropbox Q2 2025 Financial Results & Investor Presentation
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Unlocking AI with Model Context Protocol (MCP)
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity

Object Oriented Design(s) in R

  • 1. Object Oriented Design(s) in R Romain François romain@r-enthusiasts.com Chicago Local R User Group, Oct 27th , Chicago.
  • 2. Outline Lexical Scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers
  • 3. Fil rouge: bank account example Data: - The balance - Authorized overdraft Operations: - Open an account - Get the balance - Deposit - Withdraw .
  • 5. > open.account <- function(total, overdraft = 0.0){ + deposit <- function(amount) { + if( amount < 0 ) + stop( "deposits must be positive" ) + total <<- total + amount + } + withdraw <- function(amount) { + if( amount < 0 ) + stop( "withdrawals must be positive" ) + if( total - amount < overdraft ) + stop( "you cannot withdraw that much" ) + total <<- total - amount + } + balance <- function() { + total + } + list( deposit = deposit, withdraw = withdraw, + balance = balance ) + } > romain <- open.account(500) > romain$balance() [1] 500 > romain$deposit(100) > romain$withdraw(200) > romain$balance() [1] 400
  • 7. S3 classes Any R object with a class attribute Very easy Very dangerous Behaviour is added through S3 generic functions > Account <- function( total, overdraft = 0.0 ){ + out <- list( balance = total, overdraft = overdraft ) + class( out ) <- "Account" + out + } > balance <- function(x){ + UseMethod( "balance" ) + } > balance.Account <- function(x) x$balance
  • 8. S3 classes > deposit <- function(x, amount){ + UseMethod( "deposit" ) + } > deposit.Account <- function(x, amount) { + if( amount < 0 ) + stop( "deposits must be positive" ) + x$balance <- x$balance + amount + x + } > withdraw <- function(x, amount){ + UseMethod( "withdraw" ) + } > withdraw.Account <- function(x, amount) { + if( amount < 0 ) + stop( "withdrawals must be positive" ) + if( x$balance - amount < x$overdraft ) + stop( "you cannot withdraw that much" ) + x$balance <- x$balance - amount + x + }
  • 9. S3 classes Example use: > romain <- Account( 500 ) > balance( romain ) [1] 500 > romain <- deposit( romain, 100 ) > romain <- withdraw( romain, 200 ) > balance( romain ) [1] 400
  • 11. S4 classes Formal class definition Validity checking Formal generic functions and methods Very verbose, both in code and documentation
  • 12. S4 classes > setClass( "Account", + representation( + balance = "numeric", + overdraft = "numeric" + ), + prototype = prototype( + balance = 0.0, + overdraft = 0.0 + ), + validity = function(object){ + object@balance > object@overdraft + } + ) [1] "Account" > setGeneric( "balance", + function(x) standardGeneric( "balance" ) + ) [1] "balance" > setMethod( "balance", "Account", + function(x) x@balance + ) [1] "balance"
  • 13. S4 classes > setGeneric( "deposit", + function(x, amount) standardGeneric( "deposit" ) + ) [1] "deposit" > setMethod( "deposit", + signature( x = "Account", amount = "numeric" ), + function(x, amount){ + new( "Account" , + balance = x@balance + amount, + overdraft = x@overdraft + ) + } + ) [1] "deposit"
  • 14. S4 classes > romain <- new( "Account", balance = 500 ) > balance( romain ) [1] 500 > romain <- deposit( romain, 100 ) > romain <- withdraw( romain, 200 ) > balance( romain ) [1] 400
  • 16. Reference (R5) classes Real S4 classes: formalism, dispatch, ... Passed by Reference Easy to use
  • 17. Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers > Account <- setRefClass( "Account_R5", + fields = list( + balance = "numeric", + overdraft = "numeric" + ), + methods = list( + withdraw = function( amount ){ + if( amount < 0 ) + stop( "withdrawal must be positive" ) + if( balance - amount < overdraft ) + stop( "overdrawn" ) + balance <<- balance - amount + }, + deposit = function(amount){ + if( amount < 0 ) + stop( "deposits must be positive" ) + balance <<- balance + amount + } + ) + ) > x <- Account$new( balance = 10.0, overdraft = 0.0 ) > x$withdraw( 5 ) > x$deposit( 10 ) > x$balance [1] 15 Romain François Objects @ Chiacgo R User Group/Oct 2010
  • 18. Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers Real pass by reference : > borrow <- function( x, y, amount = 0.0 ){ + x$withdraw( amount ) + y$deposit( amount ) + invisible(NULL) + } > romain <- Account$new( balance = 5000, overdraft = 0.0 ) > dirk <- Account$new( balance = 3, overdraft = 0.0 ) > borrow( romain, dirk, 2000 ) > romain$balance [1] 3000 > dirk$balance [1] 2003 Romain François Objects @ Chiacgo R User Group/Oct 2010
  • 19. Outline Fil rouge lexical scoping S3 classes S4 classes Reference (R5) classes C++ classes Protocol Buffers Adding a method dynamically to a class : > Account$methods( + borrow = function(other, amount){ + deposit( amount ) + other$withdraw( amount ) + invisible(NULL) + } + ) > romain <- Account$new( balance = 5000, overdraft = 0.0 ) > dirk <- Account$new( balance = 3, overdraft = 0.0 ) > dirk$borrow( romain, 2000 ) > romain$balance [1] 3000 > dirk$balance [1] 2003 Romain François Objects @ Chiacgo R User Group/Oct 2010
  • 21. C++ classes class Account { public: Account() : balance(0.0), overdraft(0.0){} void withdraw( double amount ){ if( balance - amount < overdraft ) throw std::range_error( "no way") ; balance -= amount ; } void deposit( double amount ){ balance += amount ; } double balance ; private: double overdraft ; } ;
  • 22. C++ classes Exposing to R through Rcpp modules: RCPP_MODULE(yada){ class_<Account>( "Account") // expose the field .field_readonly( "balance", &Account::balance ) // expose the methods .method( "withdraw", &Account::withdraw ) .method( "deposit", &Account::deposit ) ; } Use it in R: > Account <- yada$Account > romain <- Account$new() > romain$deposit( 10 ) > romain$withdraw( 2 ) > romain$balance [1] 8
  • 24. Protocol Buffers Define the message type, in Account.proto : package foo ; message Account { required double balance = 1 ; required double overdraft = 2 ; } Load it into R with RProtoBuf: > require( RProtoBuf ) > loadProtoFile( "Account.proto" ) Use it: > romain <- new( foo.Account, + balance = 500, overdraft = 10 ) > romain$balance
  • 25. Questions ? Romain François http://romainfrancois.blog.free.fr romain@r-enthusiasts.com Chicago Local R User Group, Oct 27th , Chicago.