forked from lgatto/roo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
S3.Rnw
335 lines (281 loc) · 9.65 KB
/
S3.Rnw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<<knitr, echo=FALSE>>=
opts_chunk$set(tidy.opts =
list(width.cutoff = 50,
tidy = FALSE),
fig.align = 'center',
stop_on_error = 1L,
comment = NA,
prompt = TRUE)
options(width = 60)
@
\section{S3 object oriented framework}
% S4 class system introduction
\begin{frame}[t]{S3 versus S4}
\begin{block}{Differences of S3 class system to S4}
\begin{small}
\begin{itemize}
\item \textbf{Classes are not explicit} - New types are created by manually setting the \Rfunction{class()} attribute.
\item \textbf{Generics and dispatching by naming convention} - Generics work by an informal naming convention
\item \textbf{Limited introspection}
\item \textbf{No validity checking, multiple inheritance, multiple dispatch, virtual classes}
\end{itemize}
\end{small}
\bigskip
S4 class system is the de-facto standard in Bioconductor, but most of base R
is written in S3.
\end{block}
\end{frame}
\begin{frame}[fragile]
\begin{block}{Creating an object in S3}
In S3, classes are not explciit, and objects are created by setting the \Rfunction{class()}
attribute.
\end{block}
\begin{scriptsize}
<<creatClass-s3, echo=TRUE>>=
s <- list(id="example", sequence="ACCTAGAT", alphabet=c("A", "C", "G", "T"))
class(s) <- "GenericSeq"
s
names(s)
@
\end{scriptsize}
\end{frame}
\begin{frame}[fragile]{S3 generics and dispatch}
\begin{block}{Methods are created by naming convention}
The method is named as \Robject{<generic>.<class>}. The generic that is defined
by the usage of the \Robject{UseMethod()} command will look for functions of this format
in the current workspace. If not function is found it will use
\Robject{<generic>.default}.
\end{block}
\begin{scriptsize}
<<creatMethod-s3, echo=TRUE>>=
# generic
id <- function(obj, ...) UseMethod("id")
# method
id.GenericSeq <- function(obj, ...) obj$id
id(s)
@
\end{scriptsize}
\end{frame}
\begin{frame}[fragile]{S3 generics in base R}
\begin{scriptsize}
<<generics,echo=TRUE>>=
summary
x <- c(1, 4, 2, 1, 4, 2)
class(x)
summary(x)
@
\end{scriptsize}
\end{frame}
%% Cheating below because methods(summary) created an error due to '
%% in the output.
\begin{frame}[fragile]
To see what method exist for a generic:
\begin{scriptsize}
\begin{verbatim}
> methods(summary)
[1] summary.aov summary.aovlist*
[3] summary.aspell* summary.check_packages_in_dir*
[5] summary.connection summary.data.frame
[7] summary.Date summary.default
[9] summary.ecdf* summary.factor
[11] summary.glm summary.infl*
[13] summary.lm summary.loess*
[15] summary.manova summary.matrix
[17] summary.mlm* summary.nls*
[19] summary.packageStatus* summary.PDF_Dictionary*
[21] summary.PDF_Stream* summary.POSIXct
[23] summary.POSIXlt summary.ppr*
[25] summary.prcomp* summary.princomp*
[27] summary.proc_time summary.srcfile
[29] summary.srcref summary.stepfun
[31] summary.stl* summary.table
[33] summary.tukeysmooth*
see "?methods" for accessing help and source code
\end{verbatim}
\end{scriptsize}
\end{frame}
\begin{frame}[fragile]
\begin{block}{S3 dispatch}
Because there is no \Robject{summary.numeric}, the default implementation
\Robject{summary.default} is used.
\end{block}
\begin{scriptsize}
<<generics3,echo=TRUE>>=
x <- c(1, 4, 2, 1, 4, 2)
class(x)
summary(x)
summary.default(x)
@
\end{scriptsize}
\end{frame}
\begin{frame}[fragile]
\begin{scriptsize}
<<generics4,echo=TRUE>>=
y <- table(c(0, 1, 1, 0), c(1, 0, 1, 1))
class(y)
summary(y)
summary.table(y)
@
\end{scriptsize}
\end{frame}
\begin{frame}[t]{S3 methods exercises}
\small
Look at the code we have written so far, understand it, and then solve
the following exercise.
\begin{block}{\exercise}
\small
Explore some of the built-in generics and methods. Try the following commands:\\
\smallskip
\code{methods("summary")}\\
\code{methods(class="lm")}\\
\end{block}
\begin{block}{\exercise (code:\code{03_GenericSeq.R}, solution:\code{03_GenericSeq_solution.R})}
\small
Both \code{length()} and \code{rev()} are already generic functions,
but \code{alphabet()} is not.
Add these methods for class \code{GenericSeq}:
\begin{itemize}
\item \code{length()} should return the length of the DNA/RNA sequence
\item \code{alphabet()} should return the alphabet of the sequence
\item \code{rev()} should return the sequence in reverse ({\scriptsize Hint:
try to use functions \code{strsplit()} and the existing base \code{rev()} function}).
\end{itemize}
\end{block}
\comments{
<<exercise2,echo=FALSE>>=
invisible(alphabet <- function(x, ...) UseMethod("alphabet"))
invisible(alphabet.GenericSeq <- function(x, ...) x$alphabet)
invisible(rev <- function(x, ...) UseMethod("rev"))
invisible(rev.GenericSeq <- function(x, ...) paste(rev(unlist(strsplit(x$sequence, ""))), collapse=""))
invisible(seq.GenericSeq <- function(x, ...){ x$seq })
@
}
\end{frame}
% Introduce S3 inheritance
\begin{frame}[fragile]{S3 inheritance}
\begin{block}{Reusing class methods}
So far we have written methods for \code{GenericSeq} that work with any sequence type.
Now lets introduce a new class \code{DnaSeq}. We want to \textbf{inherit}
all methods from \code{GenericSeq} - to achieve this simply set the \code{class}
attribute to all applicable class names.
\end{block}
\smallskip
\begin{scriptsize}
<<seq-type,echo=TRUE>>=
setSeqSubtype <- function(s){
if (all( alphabet(s) %in% c("A","C","G","T") )) {
class(s) <- c("DnaSeq", "GenericSeq")
} else if (all( alphabet(s) %in% c("A","C","G","U") )) {
class(s) <- c("RnaSeq", "GenericSeq")
} else {
stop("Alphabet ", alphabet(s) ," is unknown.")
}
return(s)
}
s.dna <- setSeqSubtype(s)
class(s.dna)
@
\end{scriptsize}
\end{frame}
% define the DnaSeq function and show how it works
\begin{frame}[fragile]{S3 inheritance continued}
\begin{block}{\code{DnaSeq} methods}
\small
Define a \code{DnaSeq} method \code{comp()}. All \code{GenericSeq} methods still work with \code{DnaSeq} objects, but
the \code{comp()} only works with \code{DnaSeq}.
\end{block}
<<comp,echo=TRUE>>=
comp <- function(x, ...){ UseMethod("comp") }
comp.DnaSeq <- function(x, ...)
chartr("ACGT", "TGCA", seq(x))
@
\end{frame}
\begin{frame}[fragile]{S3 inheritance continued}
<<inheritance,echo=TRUE>>=
id(s) # works on GenericSeq
id(s.dna) # works on DnaSeq, GenericSeq
comp(s) # fails with error
comp(s.dna)
@
\end{frame}
\begin{frame}[fragile]{S3 inheritance continued}
\begin{block}{S3 dispatch and inheritance}
The dispatching will look for appropriate methods for all \code{x} (sub-)classes
(in order in which they are set).
\end{block}
\end{frame}
% S3 inheritance exercise
\begin{frame}[t]{S3 inheritance exercise}
Look at the inheritance code and understand how it works. Then solve the following exercise.
\begin{block}{\exercise (code: \code{04_inherit.R}, solution: \code{04_inherit_solution.R})}
Write the \code{comp()} method for \code{RnaSeq} class. Since we don't have a RNA FASTA
file you will have to make a new \code{RnaSeq} object by hand and assign the right classes
to test your code.
\bigskip
What do you notice about the S3 class system, is it easy to make mistakes? Could you also make
your RNA sequence to be of class "\code{lm}"?
\end{block}
\end{frame}
% final S3 revision
\begin{frame}
\begin{block}{S3 class system revision}
\smallskip
\begin{small}
\begin{itemize}
\item Classes are implicit (no formal class definition)
\item Making new objects is done by simply setting the \code{class} attribute
\item Making class methods is done by defining a generic function \code{functionName()} and a normal function \code{functionName.className()}.
Methods can be retrieved using the \code{methods()} function.
\item Objects can inherit multiple classes by setting the \code{class} attribute to a vector of class names
\item Many functions in base R use the S3 system
\item Easy to make new ad-hoc classes and objects, but also mistakes and inconsistencies
\end{itemize}
\end{small}
\bigskip
The S4 class system was designed to address some of these concerns.
\end{block}
\end{frame}
\begin{frame}[fragile]{Mutability in S3 and S4}
\begin{block}{Mutability}
\small
\R objects are not \textbf{mutable}; \R has a \textbf{pass-by-value} semantics,
consistently with functional programming semantics.
Whenever\footnote{\tiny{Although, in general, \R tries to avoid copying objects unless they are modified.}}
you pass an object to a function, a copy is passed as argument; changes made to the object are local to the function call;
the original object is unchanged. This is how things work for both S3 and S4 class systems.
\end{block}
\begin{scriptsize}
<<makea, echo=FALSE>>=
invisible({
setClass("GenericSeq",
representation = representation(
id = "character",
sequence = "character",
alphabet = "character"
))
setClass("DnaSeq",
contains = "GenericSeq",
prototype = prototype(
id = paste("my DNA sequence", date()),
alphabet = c("A", "C", "G", "T"),
sequence = character()))
setGeneric("seq", function(...) standardGeneric("seq"))
setMethod("seq", "GenericSeq", function(object,...) object@sequence)
a <- new("DnaSeq",sequence="ACGTAA")
})
@
<<mutability,echo=TRUE>>=
seq(a)
comp(a)
seq(a)
@
\end{scriptsize}
\end{frame}
%% % Coffee break!
%% \begin{frame}[fragile]{But before we continue...}
%% \begin{center}
%% {\Large It is time for morning coffee...}
%% \bigskip
%% (15 minute break)
%% \end{center}
%% \end{frame}