Purpose
Implement S4 Classes

> setClass("Radha", representation = representation(name = "character",
+     age = "numeric"), prototype = prototype(name = "Radha Krishna Pendyala",
+     age = 32))
[1] "Radha"
> getClass("Radha")
Class "Radha"
Slots:
Name: name age Class: character numeric > x <- new("Radha") > print(x) An object of class "Radha" Slot "name": [1] "Radha Krishna Pendyala"
Slot "age": [1] 32

Create a Generic Method, setMethod and then invoke on a object x.

> setGeneric("ambition", function(object, x) standardGeneric("ambition"))
[1] "ambition"
> setMethod("ambition", "Radha", function(object, x) "High Frequency Trading Firm")
[1] "ambition"
> x <- new("Radha")
> ambition(x)
[1] "High Frequency Trading Firm"

Create a setMethod with no reference to a class

> setMethod("ambition", "numeric", function(object, x) "Purpose : High Frequency Trading Firm")
[1] "ambition"
> ambition(10)
[1] "Purpose : High Frequency Trading Firm"

Create a setMethod with no reference to a class and having a signature

> setMethod("ambition", signature("numeric", "character"), function(object,
+     x) "My Purpose : High Frequency Trading Firm")
[1] "ambition"
> ambition(10, "vinay")
[1] "My Purpose : High Frequency Trading Firm"

Playing with setGeneric

> setGeneric("ambition1", function(x, y, ...) standardGeneric("ambition1"))
[1] "ambition1"
> setMethod("ambition1", signature("numeric"), function(x, y) "Time")
[1] "ambition1"
> setMethod("ambition1", signature("numeric", "numeric"), function(x,
+     y, ...) "Time")
[1] "ambition1"
> ambition1(10, 10)
[1] "Time"

Look carefully at these examples below to get an idea of the control Example 1

> setGeneric("temp1", function(x, y, ...) {
+     y <- standardGeneric("temp1")
+     print("In Generic")
+     y
+ })
[1] "temp1"
> setMethod("temp1", signature("numeric"), function(x, y, ...) {
+     print("In SetMethod")
+ })
[1] "temp1"
> temp1(1)
[1] "In SetMethod"
[1] "In Generic"
[1] "In SetMethod"

Example 2

> setGeneric("temp2", function(x, y, ...) {
+     print("In Generic")
+     standardGeneric("temp2")
+ })
[1] "temp2"
> setMethod("temp2", signature("numeric"), function(x, y, ...) {
+     print("In SetMethod")
+ })
[1] "temp2"
> temp2(1)
[1] "In Generic"
[1] "In SetMethod"

A generic function is invoked and then the dispatch goes to the right class.

You can specify additional arguments in the function

> setGeneric("temp3", function(x, y, ...) standardGeneric("temp3"))
[1] "temp3"
> setMethod("temp3", signature("numeric"), function(x, y, rads = "Nov",
+     ...) {
+     print(paste(x, y, rads, sep = ""))
+ })
[1] "temp3"
> temp3(19, 77)
[1] "1977Nov"
> temp3(19, 1, "Nov28")
[1] "191Nov28"

Look carefully… I am passing a names argument in to the function.