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

6.3.6 Recognising Objects, Generic Functions, and Methods

Оглавление

While we casually used already isS4() to check if an object is S4, there are multiple ways to find out if an object is S4:

 str() will report it as an S4 class,

str()

 isS4() returns TRUE, note that this is not the same as is.S3(), this is the class-specific method of the function is(),

isS4()

 pryr::otype() returns S4.

otype()

S4 generics and methods are also easy to identify because they are S4 objects with well-defined classes.

There aren't any S4 classes in the commonly used base packages (stats, graphics, utils, datasets, and base), so we will continue to use our previous example of the bank accounts.

str(my_inv_acc) ## Formal class ‘InvAcc’ [package “.GlobalEnv”] with 4 slots ## ..@ custodian :Formal class ‘Bnk’ [package “.GlobalEnv”] with 2 slots ## .. .. ..@ name : chr “HSBC Custody” ## .. .. ..@ phone: chr “123123123” ## ..@ holder : chr “Philippe” ## ..@ branch : chr “DUB01” ## ..@ opening_date: Date[1:1], format: “2019-02-21” isS4(my_inv_acc) ## [1] TRUE pryr::otype(my_inv_acc) ## [1] “S4”

The package methods provides the function is(). This function takes one object as argument, and lists all classes that the object provided as argument inherits from. Using is() with two arguments will test if an object inherits from the class specified in the second argument.

is()

is(my_inv_acc) ## [1] “InvAcc” “Acc” is(my_inv_acc, “Acc”) ## [1] TRUE

The Big R-Book

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