Methods in R Programming Language

R supports functions defined on custom data types, which can be thought of as similar to methods in object-oriented programming languages.

# Define a custom data type (similar to a struct)
rect <- function(width, height) {
  structure(list(width = width, height = height), class = "rect")
}

# This 'area' function is similar to a method with a receiver type of 'rect'
area <- function(r) {
  UseMethod("area")
}

area.rect <- function(r) {
  r$width * r$height
}

# Here's an example of a function for the 'rect' class
perim <- function(r) {
  UseMethod("perim")
}

perim.rect <- function(r) {
  2 * r$width + 2 * r$height
}

main <- function() {
  r <- rect(width = 10, height = 5)

  # Here we call the 2 functions defined for our custom type
  cat("area: ", area(r), "\n")
  cat("perim:", perim(r), "\n")

  # R doesn't have pointers, but we can demonstrate that the same functions
  # work on a copy of the object
  r_copy <- r
  cat("area: ", area(r_copy), "\n")
  cat("perim:", perim(r_copy), "\n")
}

main()

To run the program, save it as methods.R and use Rscript:

$ Rscript methods.R
area:  50 
perim: 30 
area:  50 
perim: 30

In this R example, we’ve created a custom data type rect using a constructor function. We then defined functions area and perim that use R’s S3 object-oriented system to dispatch to the appropriate method based on the class of the object.

R doesn’t have the concept of pointer and value receivers like some other languages. Instead, R uses pass-by-value semantics, but the values are often references to objects. This means that while we’re technically passing a copy of the object, both the original and the copy refer to the same underlying data.

The UseMethod function in R is used to implement generic functions, which are similar to methods in other languages. When you call a generic function, R will dispatch to the appropriate method based on the class of the first argument.

Next, we’ll look at R’s mechanisms for creating more complex data structures and functions to operate on them.