UNIT V – OBJECT-ORIENTED PROGRAMMING IN R
UNIT V – OBJECT-ORIENTED PROGRAMMING
IN R
UNIT V – OBJECT-ORIENTED PROGRAMMING IN R (Elaborated Notes)
1. INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
(OOP) IN R
Object-Oriented Programming (OOP) organizes code into objects containing
both data and methods.
R supports multiple OOP systems: S3, S4, and Reference Classes. OOP is used
to build structured,
scalable, and reusable statistical models.
2. S3 CLASS SYSTEM
S3 is the simplest OOP system in R. It is informal, flexible, and widely used.
Characteristics:
• No formal class definition
• Methods linked by naming conventions
• Supports polymorphism
Creating an S3 Object:
student <- list(name="Anu", age=20, marks=85)
class(student) <- "Student"
Generic Functions:
print(student) calls [Link]()
Advantages:
• Easy to use • Fast • Good for small programs
Limitations:
Page 1
UNIT V – OBJECT-ORIENTED PROGRAMMING IN R
• No validation • Not suitable for large systems
3. S4 CLASS SYSTEM
S4 is a formal OOP system with strict class definitions, type checking, and
inheritance.
Defining S4 Class:
setClass("Student", slots=list(name="character", age="numeric",
marks="numeric"))
Creating Object:
s1 <- new("Student", name="Anu", age=21, marks=88)
Methods:
setGeneric("display", function(object) standardGeneric("display"))
Inheritance:
setClass("Graduate", contains="Student", slots=list(degree="character"))
Advantages:
• Strict validation • Good for large applications
4. GENERIC FUNCTIONS IN S4
Steps:
1. Define class
2. Declare generic
3. Write method
Example:
Page 2
UNIT V – OBJECT-ORIENTED PROGRAMMING IN R
setGeneric("grade", function(object) standardGeneric("grade"))
5. VISUALIZATION IN R
Base Graphics: plot(), hist(), barplot()
Advanced Graphics: ggplot2
6. SIMULATION IN R
Random number generators: rnorm(), runif(), rpois()
Monte Carlo Simulation: replicate()
7. CODE PROFILING
Tools: Rprof(), summaryRprof()
8. STATISTICAL ANALYSIS IN R
Descriptive statistics: mean(), sd()
Regression: lm()
Hypothesis tests: [Link](), anova()
9. DATA MANIPULATION IN R
Base R: subset(), apply()
dplyr: filter(), select(), mutate(), summarise(), group_by()
10. SUMMARY
R supports S3 and S4 OOP, visualization tools, simulation models, profiling
techniques, and powerful
data manipulation packages like dplyr.
Page 3