Creating Generic Method
Let’s create a class bank and let’s try to create our own display() method that will use the print() method and will display the content of the class in the format specified by us.
For doing this we first have to create a generic display() function that will use the UseMethod function.
R
display <- function (obj){ UseMethod ( "print" ) } |
After creating the generic display function let’s create the display function for our class bank.
R
print.bank<- function (obj) { cat ( "Name is " , obj$name, "\n" ) cat (obj$account_no, " is the Acc no of the holder\n " ) cat (obj$saving, " is the amount of saving in the account \n " ) cat (obj$withdrawn, " is the withdrawn amount\n" ) } |
Now, let’s see the output given by this function
R
x <- list (name = "Arjun" , account_no = 1234, saving = 1500, withdrawn = 234) class (x)<- "bank" display <- function (obj){ UseMethod ( "print" ) } print.bank<- function (obj) { cat ( "Name is " , obj$name, "\n" ) cat (obj$account_no, " is the Acc no of the holder\n " ) cat (obj$saving, " is the amount of saving in the account \n " ) cat (obj$withdrawn, " is the withdrawn amount\n" ) } display (x) |
Output:
Name is Arjun 1234 is the Acc no of the holder 1500 is the amount of saving in the account 234 is the withdrawn amount
Polymorphism in R Programming
R language is evolving and it implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets you define a generic method or function for types of objects you haven’t yet defined and may never do. This means that one can use the same name for several functions with different sets of arguments and from various classes. R’s method call mechanism is generics which allows registering certain names to be treated as methods in R, and they act as dispatchers.
Contact Us