I'd like to define a new object class in R that comes with own functionality (e.g. getter for maximum value). Is it possible to realize this in R? I was thinking of something like:
test <- class() {
len = 0 # object variable1
__constructor(length=0) {
len = length # set len
}
getLength <- function() {
len # return len
}
}
and
ob = test(20) # create Objectof class test
ob.getLength() # get Length-Value of Object
R programming allows you to create a class, which is a blueprint for an object. One of the most used methods for object-oriented programming in R is the S3 system. In R, you can convert a list to a class definition.
What is the correct way to determine class in R? class(newVar) gives list .
At its heart, R is a functional programming language. But the R system includes some support for object-oriented programming (OOP).
To get you started, I'll give an example with S3
classes:
# create an S3 class using setClass:
setClass("S3_class", representation("list"))
# create an object of S3_class
S3_obj <- new("S3_class", list(x=sample(10), y=sample(10)))
Now, you can function-overload internal functions, for example, length
function to your class as (you can also operator-overload
):
length.S3_class <- function(x) sapply(x, length)
# which allows you to do:
length(S3_obj)
# x y
# 10 10
Or alternatively, you can have your own function with whatever name, where you can check if the object is of class S3_class
and do something:
len <- function(x) {
if (class(x) != "S3_class") {
stop("object not of class S3_class")
}
sapply(x, length)
}
> len(S3_obj)
# x y
# 10 10
> len(1:10)
# Error in len(1:10) : object not of class S3_class
It is a bit hard to explain S4 (like S3) as there are quite a bit of terms and things to know of (they are not difficult, just different). I suggest you go through the links provided under comments for those (and for S3 as well, as my purpose here was to show you an example of how it's done).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With