R_User
R_User

Reputation: 11082

Are Objects of own Classes possible in R?

I'm a R-newbie, and I was wondering if it is possible to create objects of own classes. When I read the "help(class)" it did not seem that classes like in Java are possible. I mean I want to have a class with methods, private variables and a constructor. For example it could look like this:

className <- class {
  # private variables
  var1 <- "standardvalue"

  var2 <- TRUE
  # Constructor
  constructor (v1, v2) {
    var1 <- v1
    var2 <- v2
  }

  # Method 1
  function sum() {
    var1 + var2
  }

  # Method 2
  function product() {
    var1 * var2
  }
}

In my main programm I want to create an Object of this Class and call it's functions. For example like this:

# Create Object
numbers <- className(10,7)

# Call functions of the Object
numbers -> sum()      # Should give "17"
numbers -> product()  # Should give "70"

Is something like this possible? So far I did not fine any example.

Thanks for your help.

Upvotes: 1

Views: 206

Answers (2)

Thomas Neitmann
Thomas Neitmann

Reputation: 2722

If you come from java and therefore are used to private and public attributes and methods I'd advise you to use the R6 package. See this link. A trivial example of a person class taken from the documentation is this:

library(R6)
Person <- R6Class("Person",
  public = list(
    name = NA,
    hair = NA,
    initialize = function(name, hair) {
      if (!missing(name)) self$name <- name
      if (!missing(hair)) self$hair <- hair
      self$greet()
    },
    set_hair = function(val) {
      self$hair <- val
    },
    greet = function() {
      cat(paste0("Hello, my name is ", self$name, ".\n"))
    }
  )
)

Here's how you can create an instance of this class:

johnDoe <- Person$new("John Doe")
johnDoe$set_hair("brown")

Note that unlike java methods are invoked using the $ operator after the object.

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

Yes, there are (at least) three OO systems to choose from in base R:

  • S3
  • S4
  • ReferenceClasses

plus additional OO-like frameworks contributed via CRAN packages such as proto.

Please do some googling for S3, S4, ReferenceClasses, OO, ..., possibly starting at rseek.org. All R programming books cover this too; my favourite is Chambers (2008) book titled "Software for Data Analysis".

Upvotes: 4

Related Questions