Last updated: 2024-04-22
Checks: 7 0
Knit directory: muse/
This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.
Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.
Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.
The command set.seed(20200712)
was run prior to running
the code in the R Markdown file. Setting a seed ensures that any results
that rely on randomness, e.g. subsampling or permutations, are
reproducible.
Great job! Recording the operating system, R version, and package versions is critical for reproducibility.
Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.
Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.
The results in this page were generated with repository version 7d1f6a3. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.
Note that you need to be careful to ensure that all relevant files for
the analysis have been committed to Git prior to generating the results
(you can use wflow_publish
or
wflow_git_commit
). workflowr only checks the R Markdown
file, but you know if there are other scripts or data files that it
depends on. Below is the status of the Git repository when the results
were generated:
Ignored files:
Ignored: .Rhistory
Ignored: .Rproj.user/
Ignored: r_packages_4.3.3/
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.
These are the previous versions of the repository in which changes were
made to the R Markdown (analysis/oo.Rmd
) and HTML
(docs/oo.html
) files. If you’ve configured a remote Git
repository (see ?wflow_git_remote
), click on the hyperlinks
in the table below to view the files as they were in that past version.
File | Version | Author | Date | Message |
---|---|---|---|---|
Rmd | 7d1f6a3 | Dave Tang | 2024-04-22 | OOP in R |
html | ee8e123 | Dave Tang | 2024-04-22 | Build site. |
Rmd | bfd5f8f | Dave Tang | 2024-04-22 | Introduction to encapsulated OOP |
html | 495b1ed | Dave Tang | 2024-04-22 | Build site. |
Rmd | 5922b9b | Dave Tang | 2024-04-22 | Add a very brief history |
html | c7022b9 | Dave Tang | 2024-04-22 | Build site. |
Rmd | 0fd2847 | Dave Tang | 2024-04-22 | Add introduction |
html | 5cdedf4 | Dave Tang | 2023-08-01 | Build site. |
Rmd | b29e9ec | Dave Tang | 2023-08-01 | Object-Oriented Programming |
From “Clean Architecture by Robert C. Martin”.
In 1966 Ole Johan Dahl and Kristen Nygaard discovered Object-Oriented Programming (OOP). They noticed that the function call stack (static) frame in ALGOL could be moved to a heap (dynamic), thereby allowing local variables declared by a function to exist long after the function returned. The function became a constructor for a class, the local variables became instance variables, and the nested fcuntions became methods. This led to the discovery of polymorphism through the disciplined use of function pointers.
From Introduction to OOP systems in Advanced R.
The main reason to use OOP is polymorphism. Polymorphism means that a developer can consider a function’s interface separately from its implementation, making it possible to use the same function form for different types of input. This is closely related to the idea of encapsulation: the user does not need to worry about details of an object because they are encapsulated behind a standard interface.
To be concrete, polymorphism is what allows summary()
to
produce different outputs for numeric and factor variables.
class(women$height)
[1] "numeric"
summary(women$height)
Min. 1st Qu. Median Mean 3rd Qu. Max.
58.0 61.5 65.0 65.0 68.5 72.0
class(ChickWeight$Diet)
[1] "factor"
summary(ChickWeight$Diet)
1 2 3 4
220 120 120 118
You could imagine summary()
containing a series of
if-else statements, but that would mean only the original author could
add new implementations (because you can’t inherit the function?). An
OOP system makes it possible for any developer to extend the interface
with implementations for new types of input.
To be more precise, OO systems call the type of an object its class, and an implementation for a specific class is called a method. Roughly speaking, a class defines what an object is and methods describe what that object can do. The class defines the fields, the data possessed by every instance of that class. Classes are organised in a hierarchy so that if a method does not exist for one class, its parent’s method is used, and the child is said to inherit behaviour. For example, in R, an ordered factor inherits from a regular factor, and a generalised linear model inherits from a linear model. The process of finding the correct method given a class is called method dispatch.
There are two main paradigms of OOP which differ in how methods and classes are related. These paradigms can be considered encapsulated and functional:
object.method(arg1, arg2)
. This is called encapsulated
because the object encapsulates both data (with fields) and behaviour
(with methods), and is the paradigm found in most popular languages,
like Python.generic(object, arg2, arg3)
. This is called
functional because from the outside it looks like a regular function
call, and internally the components are also functions.Encapsulated OOP is a programming paradigm that organises a program into objects, which are data structures consisting of attributes and methods. Objects are instantiated from a class; you can think of a class as blueprints or a factory. Each instance generated from a class has access to the class’s attributes and methods.
Classes can be inherited into sub-classes and it is this inheritance hierarchy that makes code object-oriented. Classes support code reuse in ways that other components cannot and this is the main purpose of OOP. With classes, we code by customising existing code, instead of either changing existing code in place or starting from scratch. Once you get used to programming by software customisation, writing a new program becomes a task of mixing together existing superclasses that already implement the behaviour required by your program. In many application domains, collections of superclasses are known as frameworks that implement common programming tasks as classes that are ready to be used in your programs. With frameworks, you often simply code a subclass that is specific to your purposes, and inherit from all class tree.
Most of the code I write ends up in scripts that perform a certain task. The code is interpreted starting from the first line until it reaches the last line. I believe this type of programming style is known as procedural programming, where the execution is like following a recipe from start to finish until a desired state is reached. Then there’s functional programming, which is a style that focuses on the use of functions that have certain characteristics (that make it a pure function). OOP organises a program into objects, which are data structures consisting of attributes and methods, and these objects interact with each other to solve a problem.
Base R provides three OOP systems: S3, S4, and reference classes (RC):
S3 is R’s first OOP system and is an informal implementation of functional OOP and relies on common conventions rather than formal guarantees. This makes it easy to get started with, providing a low cost way of solving many simple problems.
S4 is a formal and rigorous rewrite of S3 that requires more upfront work than S3, but in return provides more guarantees and greater encapsulation. S4 is implemented in the base {methods} package. (S3 and S4 were named according to the versions of S that they accompanied; the first two versions of S didn’t have any OOP framework, so there is no S1 or S2.)
RC implements encapsulated OO. RC objects are a special type of S4 objects that are also mutable, i.e., instead of using R’s usual copy-on-modify semantics, they can be modified in place. This makes them harder to reason about, but allows them to solve problems that are difficult to solve in the functional OOP style of S3 and S4.
There are a number of other OOP systems provided by CRAN packages:
I will use Python to illustrate some OOP concepts. Python’s main object-oriented programming tool comes via classes, which is used to implement class objects that support inheritance. A class is like a blueprint or definition for creating an object. Python classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.
The simplest form of a class definition:
class ClassName:
<statement-1>
...
<statement-N>
class MyClass:
x = 2
my_obj = MyClass()
When MyClass
was called, a new object with a distinct
namespace was generated or instantiated; my_obj
is an
instance of MyClass
. Each object generated from a class has
access to the class’s attributes and methods, and gets a namespace.
Class objects support two kinds of operations: attribute references and
instantiation. Attribute references use the standard syntax used for all
attribute references in Python: obj.name
. Valid attribute
names are all the names that were in the class’s namespace when the
class object was created. The only operations understood by instance
objects are attribute references. There are two kinds of valid attribute
names: data attributes and methods. A method is a function that belongs
to an object.
print(my_obj.x)
2
Let’s create a class with a method.
class MyClass2:
"""A simple class with a method"""
i = 1984
def __init__(self, name):
self.name = name
def f(self):
print(self)
return 'Big Brother is watching you'
x = MyClass2('Winston')
With the class definition above, MyClass2.i
and
MyClass2.f
are valid attribute references, returning an
integer and a function object, respectively. When a class defines the
special method named __init__()
, class instantiation
automatically invokes __init__()
for the newly created
class instance. This means that the __init__()
function is always executed when the class is being initiated.
Use the __init__()
function to assign values or to run
operations that are necessary when the object is being created. This
function is typically called the constructor.
Another important note regarding methods is that the instance object is automatically passed as the first argument. The following are equivalent; self is the instance object which we assigned to x.
x.f()
<__main__.MyClass2 object at 0x7fd1be6068d0>
'Big Brother is watching you'
MyClass2.f(x)
<__main__.MyClass2 object at 0x7fd1be6068d0>
'Big Brother is watching you'
Use the obj.name
syntax to add a new data attribute not
defined in the class. Use the dir()
function to return all
functions and properties of a class.
x.room_no = 101
print("\n".join(dir(x)), "\n")
__class__
__delattr__
__dict__
__dir__
__doc__
__eq__
__format__
__ge__
__getattribute__
__getstate__
__gt__
__hash__
__init__
__init_subclass__
__le__
__lt__
__module__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
__weakref__
f
i
name
room_no
However, objects need to be part of an inheritance hierarchy for the code to qualify as being truly object-oriented. The syntax for a derived class definition is:
class DerivedClassName(BaseClassName):
<statement-1>
...
<statement-N>
The syntax for multiple inheritance:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
...
<statement-N>
The search for attributes occurs depth-first, left-to-right, and not searching twice in the same class when there is an overlap in the hierarchy. But it is slightly more complex with the method resolution order changing dynamically to support cooperative calls to super().
TBC.
sessionInfo()
R version 4.3.3 (2024-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.4 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so; LAPACK version 3.10.0
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
time zone: Etc/UTC
tzcode source: system (glibc)
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] reticulate_1.36.0 lubridate_1.9.3 forcats_1.0.0 stringr_1.5.1
[5] dplyr_1.1.4 purrr_1.0.2 readr_2.1.5 tidyr_1.3.1
[9] tibble_3.2.1 ggplot2_3.5.0 tidyverse_2.0.0 workflowr_1.7.1
loaded via a namespace (and not attached):
[1] rappdirs_0.3.3 sass_0.4.9 utf8_1.2.4 generics_0.1.3
[5] lattice_0.22-5 stringi_1.8.3 hms_1.1.3 digest_0.6.35
[9] magrittr_2.0.3 timechange_0.3.0 evaluate_0.23 grid_4.3.3
[13] fastmap_1.1.1 Matrix_1.6-5 rprojroot_2.0.4 jsonlite_1.8.8
[17] processx_3.8.4 whisker_0.4.1 ps_1.7.6 promises_1.3.0
[21] httr_1.4.7 fansi_1.0.6 scales_1.3.0 jquerylib_0.1.4
[25] cli_3.6.2 rlang_1.1.3 munsell_0.5.1 withr_3.0.0
[29] cachem_1.0.8 yaml_2.3.8 tools_4.3.3 tzdb_0.4.0
[33] colorspace_2.1-0 httpuv_1.6.15 png_0.1-8 vctrs_0.6.5
[37] R6_2.5.1 lifecycle_1.0.4 git2r_0.33.0 fs_1.6.3
[41] pkgconfig_2.0.3 callr_3.7.6 pillar_1.9.0 bslib_0.7.0
[45] later_1.3.2 gtable_0.3.4 glue_1.7.0 Rcpp_1.0.12
[49] xfun_0.43 tidyselect_1.2.1 rstudioapi_0.16.0 knitr_1.46
[53] htmltools_0.5.8.1 rmarkdown_2.26 compiler_4.3.3 getPass_0.2-4