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

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

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.