Simple S4 object with method in R Project

There is a better way to create a class in R using the RC method. Only if your object don’t interact with older (S3) object.

In this simple example I’m going to create an class “Person”, then create a methode “sayMyName”
Here we defind the “Person” class with a name and an age

setClass("Person", representation(name = "character", age = "numeric"))



Create a generic function call “sayMyName”

setGeneric("sayMyName", function(object) {
  standardGeneric("sayMyName")
})



And implement the method “sayMyName” in class “Person”

setMethod("sayMyName", signature(object = "Person"), function(object) {
  paste0("My name is ",[email protected], " and I'm ",[email protected], " years old")
})



Let’s create an S4 “Person” class and call the method:

martin <- new("Person", name = "Martin Magakian", age = 28)
sayMyName(martin)

> My name is Martin Magakian and I’m 28 years old



In S4 you can access property using the @ sign:

[email protected]
  • nevaeh

    halleland nevaeh

  • nevaeh

    halleland julian

  • nevaeh

    gracie nallen
    cile allen

  • nevaeh

    Amy Berry