I have an object, suppose it's called obj
. I can call a function, obj$a()
and that works. However, when I call obj$b()
, which internally calls self$a()
, it throws an error saying that it cannot find the a
function. What can I do?
Asked
Active
Viewed 39 times
0

Shan Tulshi
- 11
-
1Might be helpful if you posted some code to make your problem reproducible. – Slavatron Aug 10 '16 at 18:49
-
R's OOP is not so fancy as all that, as far as I know. You probably want to just go `with(obj, ... do stuff ...)`. – Frank Aug 10 '16 at 18:50
-
3`self` isn't really a thing in R... – Gregor Thomas Aug 10 '16 at 18:51
-
1I'm pretty unknowledgeable about this stuff but `obj = within(list(), { a = function(x) 2*x; b = function(x,y) a(x) + y })` "works", in the sense that I can do `obj$b(11,22)`. This Q&A might be helpful: http://stackoverflow.com/questions/9521651/r-and-object-oriented-programming – Frank Aug 10 '16 at 18:52
1 Answers
2
You need to make sure that the functions share an environment / are in the same closure. You could encapsulate them in a dummy function. Look at this example:
gives_error <- list(a = function() {
print("Hello from a")
},
b = function(){
print("Hello from b")
a()
})
gives_error$b()
will_work <-
(function() {
a = function(){
print("Hello from a")
}
b = function(){
print("Hello from b")
a()
}
list(a = a, b = b)
})()
will_work$b()

AEF
- 5,408
- 1
- 16
- 30