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).