Polymorphism in R Programming

Polymorphism

R supports parametric polymorphism, enabling methods (functions) to operate on a variety of object types. Unlike class-based systems, R’s methods are tied to functions rather than classes. This mechanism allows the creation of generic methods or functions that can handle diverse object types, even ones not explicitly defined. By utilizing this, developers can use the same function name across different object classes, with behavior tailored for each.

Generic Functions in R

Polymorphism in R is achieved through generic functions, which serve as dispatchers. These functions invoke specific methods based on the class of their input objects. For instance, R’s plot() and summary() functions adapt their behavior depending on the type of object they receive as input.

Example: plot() Function

The plot() function demonstrates polymorphism by producing different visualizations depending on the type of input—numeric vectors, factors, or data frames.

Structure of plot() Function

plot

Example:

function (x, y, ...)
UseMethod("plot")

The UseMethod("plot") directive ensures the appropriate plot method is called based on the input object’s class.

Example:

methods(plot)

Output:

Viewing Available Methods for plot()

Available Methods
plot.default
plot.function
plot.lm
plot.ts
plot.factor
plot.data.frame
plot.histogram
plot.ecdf
plot.stepfun
plot.hclust
plot.prcomp
plot.density
plot.qqnorm

Single Numeric Vector: When a numeric vector is passed to plot(), it produces a line graph.

# Example: Single Numeric Vector
x <- 1:20
plot(x, type = 'l', col = 'blue')

Output:

Two Numeric Vectors: Passing two numeric vectors generates a scatter plot.

# Example: Two Numeric Vectors
x <- 1:10
y <- x * 2
plot(x, y, type = 'p', col = 'red', pch = 16)

Output:

Factor: Passing a factor to plot() produces a bar chart.

# Example: Factor
categories <- factor(c('A', 'B', 'A', 'C', 'B', 'C', 'A'))
plot(categories, col = 'green')

Output:

Data Frame: When a data frame is passed, plot() generates pairwise scatter plots for its numeric columns.

# Example: Data Frame
df <- data.frame(a = rnorm(10), b = runif(10), c = rnorm(10))
plot(df, col = 'purple', pch = 19)

Output:

Example: summary() Function

The summary() function provides summaries tailored to the input object, showcasing its polymorphic nature.

Character Vector

colors <- c("red", "blue", "green", "yellow")
summary(colors)

Output:

Length     Class      Mode
4      character character

Factor

regions <- factor(c("North", "South", "East", "North", "West"))
summary(regions)

Output:

East North South West
1     2     1     1

Numeric Data

data <- rnorm(10)
summary(data)

Output:

Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-1.900  -0.610   0.300   0.010   0.850   1.650
Creating Custom Generic Methods

Here’s how you can create your own generic methods in R:

Step 1: Define the Generic Function

display <- function(obj) {
    UseMethod("display")
}

Step 2: Define the Method for a Specific Class

display.bank <- function(obj) {
    cat("Account Holder:", obj$name, "\n")
    cat("Account Number:", obj$account_no, "\n")
    cat("Balance:", obj$balance, "\n")
    cat("Withdrawals:", obj$withdrawn, "\n")
}

Step 3: Create an Object and Assign a Class

account <- list(name = "John Doe", account_no = 12345, balance = 5000, withdrawn = 1200)
class(account) <- "bank"

Step 4: Call the Generic Function

display(account)

Output:

Account Holder: John Doe
Account Number: 12345
Balance: 5000
Withdrawals: 1200

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *