![]() |
VOOZH | about |
Abstraction refers to the process of simplifying complex systems by concealing their internal workings and only exposing the relevant details to the user. It helps in reducing complexity and allows the programmer to work with high-level concepts without worrying about the implementation.
In R, abstraction is typically achieved using:
We will see how each of these can be used for abstraction in R.
S3 classes are the most basic form of object-oriented programming in R. They are informal and dynamic, which makes them simple and easy to use for many tasks. While S3 does not enforce strict methods and classes like other OOP systems, it still allows abstraction through the use of methods and classes.
In this example, we’ve created an object person1 of class person with two attributes: name and age. The abstraction hides the internal structure and we only interact with the object using the create_person function to create the object and the print.person method to display its attributes.
Output:
Name: John
Age: 30
S4 classes are more formal and robust compared to S3. They allow you to define strict structures and provide a more powerful way to implement abstraction.
In this example, the abstraction is even more explicit: the Person class has defined slots (name and age) and we use the show method to print the object details, hiding the implementation details of the class.
Output:
Name: Bob
Age: 40
Reference classes (RC) allow for mutable objects in R, which is different from the traditional object-oriented systems like S3 and S4. Reference classes are more advanced and can be used for greater abstraction in situations requiring more control over data.
In this example, the Person class defines fields (name and age) and methods (inc_age and dec_age) that operate on these fields. The internal data is abstracted and we interact with the Person object only through its methods.
Output:
New age: 30
In this article, we explored how abstraction works in R, focusing on S3, S4 and Reference classes and demonstrate how to implement abstraction in these class systems.