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.
To run the program, save it as methods.R
and use Rscript
:
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.