Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the slots of an S4 object in R

Tags:

r

slots

s4

wavelet

I'm working with wavelets on a program and I'm used the package wavelets to create the DWT of a time series using the function dwt. This function returns an object of class dwt, which is a S4 object with many slots: W, V, levels, filter, and so on.

How can I access the W's as a vector?

like image 491
zaire90 Avatar asked Oct 27 '12 11:10

zaire90


People also ask

What is an S4 object in R?

The S4 system in R is a system for object oriented programing. Confusingly, R has support for at least 3 different systems for object oriented programming: S3, S4 and S5 (also known as reference classes).

What are slots in R?

A slot name can be any non-empty string, but if the name is not made up of letters, numbers, and . , it needs to be quoted (by backticks or single or double quotes). In the case of the slot function, name can be any expression that evaluates to a valid slot in the class definition.

What is S3 and S4 in R?

The S3 and S4 software in R are two generations implementing functional object-oriented programming. S3 is the original, simpler for initial programming but less general, less formal and less open to validation. The S4 formal methods and classes provide these features but require more programming.

How are S4 classes better than S3 classes?

S4 Class is stricter, conventional, and closely related to Object-Oriented concepts. The classes are represented by the formal class definitions of S4. More specifically, S4 has setter and getter functions for methods and generics. As compared to the S3 class, S4 can be able to facilitate multiple dispatches.


2 Answers

@ will let you access the slots of an S4 object.

So if your object is called wave, then wave@W should get you your vector.

Note that often the best way to do this is to not access the slot directly but rather through an accessor function (e.g. coefs() rather than digging out the coefficients with $ or @). However, often such functions do not exist so you have to access the slots directly. This will mean that your code breaks if the internal implementation changes, however.

like image 83
Ari B. Friedman Avatar answered Sep 28 '22 18:09

Ari B. Friedman


Ari B. Friedman's answer is good.

But please keep in mind that using @ to access the slots of an S4 object may not be a good practice. See the discuss here: Is it bad practice to access S4 objects slots directly using @?

like image 28
Xiaorui Zhu Avatar answered Sep 28 '22 16:09

Xiaorui Zhu