Object-oriented programming in R: creating classes, methods, inheritance

In R, you can perform object-oriented programming (OOP) by creating classes, methods, and inheritance. Here are some examples:

## Creating classes
# Define a class for a person
setClass(“Person”,
slots = list(name = “character”, age = “numeric”))

# Create an instance of the class
person1 <- new("Person", name = "John", age = 30) In this code, we define a class called `Person` using the `setClass()` function. We specify two slots for the class, `name` and `age`, using the `slots` argument. We then create an instance of the class called `person1` using the `new()` function, passing in the class name and values for the slots. ## Methods # Define a method to print the person's name setMethod("print", "Person", function(x) { cat("Name:", x@name, "\n") }) # Use the method to print the person's name print(person1) In this code, we define a method called `print` for the `Person` class using the `setMethod()` function. We specify the class and the function to execute when the method is called. Inside the function, we use the `cat()` function to print the person's name. We then use the `print()` function to call the method and print the person's name. ## Inheritance # Define a class for astudent, inheriting from the Person class setClass("Student", slots = list(name = "character", age = "numeric", major = "character"), contains = "Person") # Create an instance of the student class student1 <- new("Student", name = "Jane", age = 20, major = "Biology") # Use the print method to print the student's name and major print(student1) In this code, we define a class called `Student` using the `setClass()` function. We specify three slots for the class, `name`, `age`, and `major`, and we indicate that the `Student` class inherits from the `Person` class using the `contains` argument. We then create an instance of the `Student` class called `student1` using the `new()` function, passing in the class name and values for the slots. We can use the `print()` method we defined earlier to print the `Student` object. Since the `Student` class inherits from `Person`, it has access to the `print()` method defined for `Person`, so we can print the person's name using the `cat()` function as before. But we can also print the student's major by accessing the slot using the `@` operator. Note that there are many other techniques and concepts in OOP, including encapsulation, polymorphism, and class constructors and destructors. You can find more information on these topicsand other advanced OOP concepts in the R documentation or online tutorials and resources.