Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 200

6.3.1 Creating S4 Objects

Оглавление

While an S3 object can be used without defining it first, to create a valid S4 object, we need at least:

 Name: An alpha-numeric string that identifies the class

 Representation: A list of slots (or attributes), giving their names and classes. For example, a person class might be represented by a character name and a numeric age, as follows: representation(name = “character”, age = “numeric”)

 Inheritance: A character vector of classes that it inherits from, or in S4 terminology, contains. Note that S4 supports multiple inheritance, but this should be used with extreme caution as it makes method lookup extremely complicated.

S4 objects are created with the function setClass().

setClass()

# Create the object type Acc to hold bank-accounts: setClass(“Acc”, representation(holder = “character”, branch = “character”, opening_date = “Date”)) # Create the object type Bnk (bank): setClass(“Bnk”, representation(name = “character”, phone = “numeric”)) # Define current account as a child of Acc: setClass(“CurrAcc”, representation(interest_rate = “numeric”, balance = “numeric”), contains = “Acc”) # Define investment account as a child of Acc setClass(“InvAcc”, representation(custodian = “Bnk”), contains = “Acc”)

This will only create the definition of the objects. So, to create a variable in your code that can be used to put your data or models inside, instances have to be created with the function new().

new()

The Big R-Book

Подняться наверх