Mark Bower
Mark Bower

Reputation: 589

In R, modify a value within a class

Maybe I am thinking of R classes as if they were classes in C or Java, but I cannot seem to modify values:

test <- function() {

  inc <- function() {
    x <- attr( obj, "x" )
    x <- x + 1
    print(x)
    attr( obj, "x" ) <- x
    return( obj )
  }

  obj <- list(inc=inc)
  attr( obj, "x" ) <- 1
  class(obj) <- c('test')
  return( obj )
}

When I run this:

> t <- test()
> t <- t$inc()
[1] 2
> t <- t$inc()
[1] 2

It is as if the original class object cannot be modified.

Upvotes: 2

Views: 75

Answers (1)

Nairolf
Nairolf

Reputation: 2556

One can use the lexical scoping mechanism of R to achieve a C or Java like object orientation. Use <<- to assign a value in the parent environment.

A simplified version of your examples is below.

test <- function() {
    inc <- function() {
        x <<- x + 1
        print(x)
    }
    x <- 1
    list(inc=inc)
}
obj <- test()
obj$inc()
[1] 2
obj$inc()
[1] 3

See also ?refClass-class for what is called "reference classes" in R.

Upvotes: 2

Related Questions