SlideShare a Scribd company logo
1 of 36
Download to read offline
An object is a data structure having some attributes and methods which act on its
attributes.
Class is a blueprint for the object. We can think of class like a sketch (prototype) of a house.
It contains all the details about the floors, doors, windows etc. Based on these descriptions
we build the house.
House is the object. As, many houses can be made from a description, we can create many
objects from a class.
An object is also called an instance of a class and the process of creating this object is
called instantiation.
S3 class is somewhat primitive in nature. It lacks a formal definition and object of this class can be created simply
by adding a class attribute to it.
Example 1: S3 class
> # create a list with required components
> s <- list(name = "John", age = 21, GPA = 3.5)
> # name the class appropriately
> class(s) <- "student"
Above example creates a S3 class with the given list.
S4 class are an improvement over the S3 class. They have a formally defined structure which helps in making
object of the same class look more or less similar.
Class components are properly defined using the function and objects are created using the
function.
Example 2: S4 class
< setClass("student", slots=list(name="character", age="numeric", GPA="numeric"))
It is more similar to the object oriented programming we are used to seeing in other major programming
languages.
Reference classes are basically S4 classed with an environment added to it.
Example 3: Reference class
< setRefClass("student")
S3 class is the most popular and prevalent class in R programming language.
Most of the classes that come predefined in R are of this type. The fact that it is simple and easy to
implement.
How to define S3 class and create S3
objects?
S3 class has no formal, predefined definition.
Basically, a list with its class attribute set to some class name, is an S3 object. The components of the list
become the member variables of the object.
Following is a simple example of how an S3 object of class student can be created.
> # create a list with required components
> s <- list(name = "John", age = 21, GPA = 3.5)
> # name the class appropriately
> class(s) <- "student"
> # That's it! we now have an object of class "student"
> s
$name
[1] "John"
$age
[1] 21
$GPA
[1] 3.5
attr(,"class")
[1] "student"
How to use constructors to create objects?
Tt is a good practice to use a function with the same name as class (not a necessity) to create objects.
This will bring some uniformity in the creation of objects and make them look similar. We can also add
some integrity check on the member attributes
this example we use the function to set the class attribute of the object.
# a constructor function for the "student" class
student <- function(n,a,g) {
# we can add our own integrity checks
if(g>4 || g<0) stop("GPA must be between 0 and 4")
value <- list(name = n, age = a, GPA = g)
# class can be set using class() or attr() function
attr(value, "class") <- "student"
value
}
Here is a sample run where we create objects using this constructor.
> s <- student("Paul", 26, 3.7)
> s
$name
[1] "Paul"
$age
[1] 26
$GPA
[1] 3.7
attr(,"class")
[1] "student"
> class(s)
[1] "student"
> s <- student("Paul", 26, 5)
Error in student("Paul", 26, 5) : GPA must be between 0 and 4
> # these integrity check only work while creating the object using constructor
> s <- student("Paul", 26, 2.5)
> # it's up to us to maintain it or not
> s$GPA <- 5
Methods and Generic Functions
simply write the name of the object, its internals get printed.
In interactive mode, writing the name alone will print it using the function.
> s
$name
[1] "Paul"
$age
[1] 26
$GPA
[1] 3.7
attr(,"class")
[1] "student"
How to write your own method?
implement a method ourself.
print.student <- function(obj) {
cat(obj$name, "n")
cat(obj$age, "years oldn")
cat("GPA:", obj$GPA, "n")
}
Now this method will be called whenever we an object of class " ".
In S3 system, methods do not belong to object or class, they belong to generic functions. This will work as
long as the class of the object is set.
> # our above implemented method is called
> s
Paul
26 years old
GPA: 3.7
> # removing the class attribute will restore as previous
> unclass(s)
$name
[1] "Paul"
$age
[1] 26
$GPA
[1] 3.7
Unlike S3 classes and objects which lacks formal definition, we look at S4 class which is stricter in the sense that
it has a formal definition and a uniform way to create objects.
How to define S4 Class?
S4 class is defined using the setClass() function.
In R terminology, member variables are called slots. While defining a class, we need to set the name and the
slots (along with class of the slot) it is going to have.
Example 1: Definition of S4 class
setClass("student", slots=list(name="character", age="numeric", GPA="numeric"))
In the above example, we defined a new class called student along with three slots it’s going to have name, age
and GPA.
There are other optional arguments of setClass() which you can explore in the help section with ?setClass.
How to create S4 objects?
S4 objects are created using the new() function.
Example 2: Creation of S4 object
> # create an object using new()
> # provide the class name and value for slots
> s <- new("student",name="John", age=21, GPA=3.5)
> s
An object of class "student"
Slot "name":
[1] "John"
Slot "age":
[1] 21
Slot "GPA":
[1] 3.5
We can check if an object is an S4 object through the function isS4().
> isS4(s)
[1] TRUE
How to access and modify slot?
Just as components of a list are accessed using $, slot of an object are accessed using @.
Accessing slot
> s@name
[1] "John"
> s@GPA
[1] 3.5
> s@age
[1] 21
Modifying slot directly
A slot can be modified through reassignment.
> # modify GPA
> s@GPA <- 3.7
> s
An object of class "student"
Slot "name":
[1] "John"
Slot "age":
[1] 21
Slot "GPA":
How to write your own method?
We can write our own method using setMethod() helper function.
For example, we can implement our class method for the show() generic as follows.
setMethod("show",
"student",
function(object) {
cat(object@name, "n")
cat(object@age, "years oldn")
cat("GPA:", object@GPA, "n")
}
)
Now, if we write out the name of the object in interactive mode as before, the above code is executed.
> s <- new("student",name="John", age=21, GPA=3.5)
> s # this is same as show(s)
John
21 years old
GPA: 3.5
S3 classes and s4 classes

More Related Content

What's hot (20)

MySQL Functions
MySQL FunctionsMySQL Functions
MySQL Functions
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Data Structures
Data StructuresData Structures
Data Structures
 
Data Visualization(s) Using Python
Data Visualization(s) Using PythonData Visualization(s) Using Python
Data Visualization(s) Using Python
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Application of Data structure
Application of Data structureApplication of Data structure
Application of Data structure
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
R data-import, data-export
R data-import, data-exportR data-import, data-export
R data-import, data-export
 
3. mining frequent patterns
3. mining frequent patterns3. mining frequent patterns
3. mining frequent patterns
 
Class diagrams
Class diagramsClass diagrams
Class diagrams
 
Python list
Python listPython list
Python list
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
 
Lists
ListsLists
Lists
 
Data Exploration and Visualization with R
Data Exploration and Visualization with RData Exploration and Visualization with R
Data Exploration and Visualization with R
 

Similar to S3 classes and s4 classes

Similar to S3 classes and s4 classes (20)

Ch2
Ch2Ch2
Ch2
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Oop scala
Oop scalaOop scala
Oop scala
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Oop java
Oop javaOop java
Oop java
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
python.pptx
python.pptxpython.pptx
python.pptx
 
creating objects and Class methods
creating objects and Class methodscreating objects and Class methods
creating objects and Class methods
 
Class methods
Class methodsClass methods
Class methods
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Simple class and object examples in java
Simple class and object examples in javaSimple class and object examples in java
Simple class and object examples in java
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)
 
Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
 

More from Ashwini Mathur

Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r Ashwini Mathur
 
R programming lab 3 - jupyter notebook
R programming lab   3 - jupyter notebookR programming lab   3 - jupyter notebook
R programming lab 3 - jupyter notebookAshwini Mathur
 
R programming lab 2 - jupyter notebook
R programming lab   2 - jupyter notebookR programming lab   2 - jupyter notebook
R programming lab 2 - jupyter notebookAshwini Mathur
 
R programming lab 1 - jupyter notebook
R programming lab   1 - jupyter notebookR programming lab   1 - jupyter notebook
R programming lab 1 - jupyter notebookAshwini Mathur
 
R for statistics session 1
R for statistics session 1R for statistics session 1
R for statistics session 1Ashwini Mathur
 
Object oriented programming in r
Object oriented programming in r Object oriented programming in r
Object oriented programming in r Ashwini Mathur
 
Linear programming optimization in r
Linear programming optimization in r Linear programming optimization in r
Linear programming optimization in r Ashwini Mathur
 
Introduction to python along with the comparitive analysis with r
Introduction to python   along with the comparitive analysis with r Introduction to python   along with the comparitive analysis with r
Introduction to python along with the comparitive analysis with r Ashwini Mathur
 
Example 2 summerization notes for descriptive statistics using r
Example   2    summerization notes for descriptive statistics using r Example   2    summerization notes for descriptive statistics using r
Example 2 summerization notes for descriptive statistics using r Ashwini Mathur
 
Descriptive statistics assignment
Descriptive statistics assignment Descriptive statistics assignment
Descriptive statistics assignment Ashwini Mathur
 
Descriptive analytics in r programming language
Descriptive analytics in r programming languageDescriptive analytics in r programming language
Descriptive analytics in r programming languageAshwini Mathur
 
Data analysis for covid 19
Data analysis for covid 19Data analysis for covid 19
Data analysis for covid 19Ashwini Mathur
 
Correlation and linear regression
Correlation and linear regression Correlation and linear regression
Correlation and linear regression Ashwini Mathur
 
Calling c functions from r programming unit 5
Calling c functions from r programming    unit 5Calling c functions from r programming    unit 5
Calling c functions from r programming unit 5Ashwini Mathur
 
Anova (analysis of variance) test
Anova (analysis of variance) test Anova (analysis of variance) test
Anova (analysis of variance) test Ashwini Mathur
 

More from Ashwini Mathur (19)

Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r
 
Rpy2 demonstration
Rpy2 demonstrationRpy2 demonstration
Rpy2 demonstration
 
Rpy package
Rpy packageRpy package
Rpy package
 
R programming lab 3 - jupyter notebook
R programming lab   3 - jupyter notebookR programming lab   3 - jupyter notebook
R programming lab 3 - jupyter notebook
 
R programming lab 2 - jupyter notebook
R programming lab   2 - jupyter notebookR programming lab   2 - jupyter notebook
R programming lab 2 - jupyter notebook
 
R programming lab 1 - jupyter notebook
R programming lab   1 - jupyter notebookR programming lab   1 - jupyter notebook
R programming lab 1 - jupyter notebook
 
R for statistics session 1
R for statistics session 1R for statistics session 1
R for statistics session 1
 
R for statistics 2
R for statistics 2R for statistics 2
R for statistics 2
 
Play with matrix in r
Play with matrix in rPlay with matrix in r
Play with matrix in r
 
Object oriented programming in r
Object oriented programming in r Object oriented programming in r
Object oriented programming in r
 
Linear programming optimization in r
Linear programming optimization in r Linear programming optimization in r
Linear programming optimization in r
 
Introduction to python along with the comparitive analysis with r
Introduction to python   along with the comparitive analysis with r Introduction to python   along with the comparitive analysis with r
Introduction to python along with the comparitive analysis with r
 
Example 2 summerization notes for descriptive statistics using r
Example   2    summerization notes for descriptive statistics using r Example   2    summerization notes for descriptive statistics using r
Example 2 summerization notes for descriptive statistics using r
 
Descriptive statistics assignment
Descriptive statistics assignment Descriptive statistics assignment
Descriptive statistics assignment
 
Descriptive analytics in r programming language
Descriptive analytics in r programming languageDescriptive analytics in r programming language
Descriptive analytics in r programming language
 
Data analysis for covid 19
Data analysis for covid 19Data analysis for covid 19
Data analysis for covid 19
 
Correlation and linear regression
Correlation and linear regression Correlation and linear regression
Correlation and linear regression
 
Calling c functions from r programming unit 5
Calling c functions from r programming    unit 5Calling c functions from r programming    unit 5
Calling c functions from r programming unit 5
 
Anova (analysis of variance) test
Anova (analysis of variance) test Anova (analysis of variance) test
Anova (analysis of variance) test
 

Recently uploaded

VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 

Recently uploaded (20)

VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 

S3 classes and s4 classes

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. An object is a data structure having some attributes and methods which act on its attributes. Class is a blueprint for the object. We can think of class like a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.
  • 9.
  • 10.
  • 11.
  • 12. S3 class is somewhat primitive in nature. It lacks a formal definition and object of this class can be created simply by adding a class attribute to it. Example 1: S3 class > # create a list with required components > s <- list(name = "John", age = 21, GPA = 3.5) > # name the class appropriately > class(s) <- "student" Above example creates a S3 class with the given list.
  • 13. S4 class are an improvement over the S3 class. They have a formally defined structure which helps in making object of the same class look more or less similar. Class components are properly defined using the function and objects are created using the function. Example 2: S4 class < setClass("student", slots=list(name="character", age="numeric", GPA="numeric"))
  • 14. It is more similar to the object oriented programming we are used to seeing in other major programming languages. Reference classes are basically S4 classed with an environment added to it. Example 3: Reference class < setRefClass("student")
  • 15.
  • 16. S3 class is the most popular and prevalent class in R programming language. Most of the classes that come predefined in R are of this type. The fact that it is simple and easy to implement.
  • 17. How to define S3 class and create S3 objects? S3 class has no formal, predefined definition. Basically, a list with its class attribute set to some class name, is an S3 object. The components of the list become the member variables of the object.
  • 18. Following is a simple example of how an S3 object of class student can be created. > # create a list with required components > s <- list(name = "John", age = 21, GPA = 3.5) > # name the class appropriately > class(s) <- "student" > # That's it! we now have an object of class "student"
  • 19. > s $name [1] "John" $age [1] 21 $GPA [1] 3.5 attr(,"class") [1] "student"
  • 20. How to use constructors to create objects? Tt is a good practice to use a function with the same name as class (not a necessity) to create objects. This will bring some uniformity in the creation of objects and make them look similar. We can also add some integrity check on the member attributes
  • 21. this example we use the function to set the class attribute of the object. # a constructor function for the "student" class student <- function(n,a,g) { # we can add our own integrity checks if(g>4 || g<0) stop("GPA must be between 0 and 4") value <- list(name = n, age = a, GPA = g) # class can be set using class() or attr() function attr(value, "class") <- "student" value }
  • 22. Here is a sample run where we create objects using this constructor. > s <- student("Paul", 26, 3.7) > s $name [1] "Paul" $age [1] 26 $GPA [1] 3.7
  • 23. attr(,"class") [1] "student" > class(s) [1] "student" > s <- student("Paul", 26, 5) Error in student("Paul", 26, 5) : GPA must be between 0 and 4 > # these integrity check only work while creating the object using constructor > s <- student("Paul", 26, 2.5) > # it's up to us to maintain it or not > s$GPA <- 5
  • 24. Methods and Generic Functions simply write the name of the object, its internals get printed. In interactive mode, writing the name alone will print it using the function. > s $name [1] "Paul" $age [1] 26 $GPA [1] 3.7 attr(,"class") [1] "student"
  • 25. How to write your own method? implement a method ourself. print.student <- function(obj) { cat(obj$name, "n") cat(obj$age, "years oldn") cat("GPA:", obj$GPA, "n") } Now this method will be called whenever we an object of class " ". In S3 system, methods do not belong to object or class, they belong to generic functions. This will work as long as the class of the object is set.
  • 26. > # our above implemented method is called > s Paul 26 years old GPA: 3.7 > # removing the class attribute will restore as previous > unclass(s) $name [1] "Paul" $age [1] 26 $GPA [1] 3.7
  • 27.
  • 28. Unlike S3 classes and objects which lacks formal definition, we look at S4 class which is stricter in the sense that it has a formal definition and a uniform way to create objects.
  • 29. How to define S4 Class? S4 class is defined using the setClass() function. In R terminology, member variables are called slots. While defining a class, we need to set the name and the slots (along with class of the slot) it is going to have. Example 1: Definition of S4 class setClass("student", slots=list(name="character", age="numeric", GPA="numeric")) In the above example, we defined a new class called student along with three slots it’s going to have name, age and GPA. There are other optional arguments of setClass() which you can explore in the help section with ?setClass.
  • 30. How to create S4 objects? S4 objects are created using the new() function. Example 2: Creation of S4 object > # create an object using new() > # provide the class name and value for slots > s <- new("student",name="John", age=21, GPA=3.5) > s An object of class "student" Slot "name": [1] "John" Slot "age": [1] 21 Slot "GPA": [1] 3.5
  • 31. We can check if an object is an S4 object through the function isS4(). > isS4(s) [1] TRUE
  • 32. How to access and modify slot? Just as components of a list are accessed using $, slot of an object are accessed using @. Accessing slot > s@name [1] "John" > s@GPA [1] 3.5 > s@age [1] 21
  • 33. Modifying slot directly A slot can be modified through reassignment. > # modify GPA > s@GPA <- 3.7 > s An object of class "student" Slot "name": [1] "John" Slot "age": [1] 21 Slot "GPA":
  • 34. How to write your own method? We can write our own method using setMethod() helper function. For example, we can implement our class method for the show() generic as follows. setMethod("show", "student", function(object) { cat(object@name, "n") cat(object@age, "years oldn") cat("GPA:", object@GPA, "n") } )
  • 35. Now, if we write out the name of the object in interactive mode as before, the above code is executed. > s <- new("student",name="John", age=21, GPA=3.5) > s # this is same as show(s) John 21 years old GPA: 3.5