r - Using "[[ ]]" notation for reference class methods -
while experimenting new reference classes in r noticed odd behaviour if use "[[ ]]" notation methods (x[["dosomething"]] instead of x$dosomething). notation works fields, thought wouldn't work methods until found if execute "class(x$dosomething)" can use "[[ ]]" afterwards. simple example below illustrates point.
setrefclass("number", fields = list( value = "numeric" ), methods = list( addone = function() { value <<- value + 1 } ) ) x <- new("number", value = 1) x[['value']] # 1 x[["addone"]]() # error: attempt apply non-function class(x[["addone"]]) # null class(x$addone) # "refmethoddef" # following works! x[["addone"]]() # sets x$value = 2 class(x[["addone"]]) # "refmethoddef"
the reason encountered because want group objects in list , create "applymethod" function applies specified method on each of objects within. therefore, need specify method string. have ideas how can achieve this?
here's class
.a <- setrefclass("a", fields=list(x="numeric"), methods=list(foo=function() x))
if had instance a
, wanted construct call 'foo' method using '$' could
eval(substitute(a$fun(), list(fun="foo")))
so i'll create class alist
meant have list of elements of class a
(this enforced programmatically), , has .delegate
method that'll apply arbitrary method elements of list. i'll add method delegates foo
.
.delegate <- function(fun, ...) { lapply(elts, function(elt, ...) { eval(substitute(elt$fun(...), list(fun=fun, ...))) }) } .alist <- setrefclass("alist", fields=list(elts="list"), methods=list( initialize = function(...) callsuper(elts=list(...)), .delegate = .delegate, foo=function() .delegate("foo")))
and use it
> alist <- .alist$new(.a$new(x=1), .a$new(x=2)) > alist$foo() [[1]] [1] 1 [[2]] [1] 2
Comments
Post a Comment