Reputation: 643
I can make a list containing a function, e.g.,
foo <- list(value=1, func=function(x) x+1)
Then foo$func(3)
gives 4
. But is it possible for the $func
function to have access the $value
element in the same list? I've tried the following, which is (obviously) wrong:
foo <- list(value=1, func=function(x) x+value)
foo$func(3)
# Error in foo$func(3) : object 'value' not found
I know the following codes work:
bar <- list(value=1, func=function(FOO,x) x+FOO$value)
bar$func(bar, 3)
# [1] 4
func <- function(FOO,x) x+FOO$value
func(foo,3)
# [1] 4
But I want to use the foo$func(3)
syntax, rather than func(foo,3)
, for some reasons. Can this be achieved by R?
Thank you.
EDIT
Beside the helpful answers below, ?ReferenceClasses
is also useful.
Upvotes: 3
Views: 102
Reputation: 9087
This can be done with the proto
package.
library("proto")
foo <- proto(value = 1, func = function(., x) x + .$value)
foo$func(3)
#> [1] 4
foo$value <- 7
foo$func(10)
#> [1] 17
Upvotes: 3
Reputation: 3923
foo <- list(value = 1, func = function(x) x + foo$value)
foo$func(3)
Is this good enough for you?
Upvotes: 5