chan1142
chan1142

Reputation: 643

Access an element of list within itself in R

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

Answers (2)

Paul
Paul

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

RolandASc
RolandASc

Reputation: 3923

foo <- list(value = 1, func = function(x) x + foo$value)
foo$func(3)

Is this good enough for you?

Upvotes: 5

Related Questions