Is it possible to define classes of objects that have their own methods in R

I would like to define a new class of objects in R that comes with its own functionality (e.g. getter for maximum value). Can this be implemented 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
+5
source share
2 answers

To get started, I will give an example with S3classes:

# 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 overload internal functions, for example length, in your class (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 any name, where you can check if the object is a class S3_classand 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

S4 (, S3), , ( , ). , ( S3, , ).

+8

R ,

test = function() {
  len = 0
  set_length = function(l = 0) len <<-l
  get_length = function() len
  return(list(set_length=set_length, get_length=get_length))
}

:

R> m = test()
R> m$set_length(10)
R> m$get_length()
[1] 10
R> m$set_length()
R> m$get_length()
[1] 0
+6

All Articles