Skip to content

Instantly share code, notes, and snippets.

@joshbode
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save joshbode/243a4ae33281cf4e8409 to your computer and use it in GitHub Desktop.

Select an option

Save joshbode/243a4ae33281cf4e8409 to your computer and use it in GitHub Desktop.
R Reference Classes - Simple Class Factory
A = setRefClass("A",
methods=list(
hello=identity,
process=function(x) {-x}
)
)
B = setRefClass("B",
contains='A',
methods=list(
process=function(x) {
y = callSuper(x)
y = y * 2
return(y)
}
)
)
data = list(
list(x=runif(10), method="apple"),
list(x=runif(10), method="banana"),
list(x=runif(10), method="apple")
)
# class factory map
class_map = list("apple"=A, "banana"=B)
class_factory = function(name) {
class_map[[name]]
}
lapply(data, function(e) {
# get correct class
obj = class_factory(e$method)()
y = obj$process(e$x)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment