SlideShare a Scribd company logo
1 of 25
Download to read offline
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

What's hot

The Ring programming language version 1.9 book - Part 38 of 210
The Ring programming language version 1.9 book - Part 38 of 210The Ring programming language version 1.9 book - Part 38 of 210
The Ring programming language version 1.9 book - Part 38 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 30 of 185
The Ring programming language version 1.5.4 book - Part 30 of 185The Ring programming language version 1.5.4 book - Part 30 of 185
The Ring programming language version 1.5.4 book - Part 30 of 185Mahmoud Samir Fayed
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBjorgeortiz85
 
The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 23 of 84
The Ring programming language version 1.2 book - Part 23 of 84The Ring programming language version 1.2 book - Part 23 of 84
The Ring programming language version 1.2 book - Part 23 of 84Mahmoud Samir Fayed
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
Seductions of Scala
Seductions of ScalaSeductions of Scala
Seductions of ScalaDean Wampler
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 21 of 88
The Ring programming language version 1.3 book - Part 21 of 88The Ring programming language version 1.3 book - Part 21 of 88
The Ring programming language version 1.3 book - Part 21 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184Mahmoud Samir Fayed
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 
Streams and lambdas the good, the bad and the ugly
Streams and lambdas the good, the bad and the uglyStreams and lambdas the good, the bad and the ugly
Streams and lambdas the good, the bad and the uglyPeter Lawrey
 

What's hot (20)

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

Similar to Object Oriented Design(s) in R

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
The Future Shape of Ruby Objects
The Future Shape of Ruby ObjectsThe Future Shape of Ruby Objects
The Future Shape of Ruby ObjectsChris Seaton
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Clean Architecture Applications in Python
Clean Architecture Applications in PythonClean Architecture Applications in Python
Clean Architecture Applications in PythonSubhash Bhushan
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Chris Richardson
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用Felinx Lee
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Android DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureAndroid DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureiMasters
 
exportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxexportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxDaniel Gilhousen
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Apache Spark for Library Developers with William Benton and Erik Erlandson
 Apache Spark for Library Developers with William Benton and Erik Erlandson Apache Spark for Library Developers with William Benton and Erik Erlandson
Apache Spark for Library Developers with William Benton and Erik ErlandsonDatabricks
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 

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

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

More from Romain Francois (20)

R/C++
R/C++R/C++
R/C++
 
dplyr and torrents from cpasbien
dplyr and torrents from cpasbiendplyr and torrents from cpasbien
dplyr and torrents from cpasbien
 
dplyr use case
dplyr use casedplyr use case
dplyr use case
 
dplyr
dplyrdplyr
dplyr
 
user2015 keynote talk
user2015 keynote talkuser2015 keynote talk
user2015 keynote talk
 
SevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittrSevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittr
 
dplyr
dplyrdplyr
dplyr
 
Data manipulation with dplyr
Data manipulation with dplyrData manipulation with dplyr
Data manipulation with dplyr
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
R and C++
R and C++R and C++
R and C++
 
R and cpp
R and cppR and cpp
R and cpp
 
Rcpp attributes
Rcpp attributesRcpp attributes
Rcpp attributes
 
Rcpp is-ready
Rcpp is-readyRcpp is-ready
Rcpp is-ready
 
Rcpp
RcppRcpp
Rcpp
 
Integrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBufIntegrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBuf
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
RProtoBuf: protocol buffers for R
RProtoBuf: protocol buffers for RRProtoBuf: protocol buffers for R
RProtoBuf: protocol buffers for R
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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.