Skip to content

Instantly share code, notes, and snippets.

@wch
Created May 9, 2014 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/7bb50e22d873da689b05 to your computer and use it in GitHub Desktop.
Save wch/7bb50e22d873da689b05 to your computer and use it in GitHub Desktop.
Non-reference class in R with class methods
Class6 <- function(...) {
structure(list(...), class = "Class6")
}
# Methods for the class
Class6_methods <- list(
sum_xy = function(self) {
self$x + self$y
},
inc_x = function(self, amount = 1) {
self$x <- self$x + amount
self
}
)
# Redefine $ so that you can use it to invoke class methods
`$.Class6` <- function(x, name) {
# This is a little crude, but it works
if (name %in% names(x)) {
res <- .subset2(x, name)
if (is.function(res)) {
# If it's a function, curry it
function(...) res(x, ...)
} else {
res
}
} else if (name %in% names(Class6_methods)) {
# Return a curried function
fun <- Class6_methods[[name]]
function(...) fun(x, ...)
} else {
stop('Member and method with name ', name, ' not found.')
}
}
`[[.Class6` <- `$.Class6`
# Create a new object z, which also has an individual method
z <- Class6(
x=1,
y=2,
prod_xy = function(self) self$x * self$y
)
z
z$x
z$sum_xy()
z$inc_x
z$inc_x()$inc_x(4)
z$sum_xy()
z <- z$inc_x()$inc_x(4)
z$sum_xy()
z$prod_xy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment