Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define object classes that have own methods in R [closed]

Tags:

object

oop

r

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
like image 249
R_User Avatar asked Mar 06 '13 09:03

R_User


People also ask

Can you define classes in R?

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.

Which method is used to determine class of an R object?

What is the correct way to determine class in R? class(newVar) gives list .

Can you do object oriented programming in R?

At its heart, R is a functional programming language. But the R system includes some support for object-oriented programming (OOP).


1 Answers

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

like image 79
Arun Avatar answered Oct 14 '22 22:10

Arun