r - How to avoid nested function definitions and still use <<- operator -


suppose have these 2 functions:

finner<-function() {    # complicated stuff, and...     i<<-i+1 }  fouter<-function() {     i<-0     finner()     print(i) } 

calling fouter() produces error: error in finner() : object 'i' not found. know, 1 way of fixing re-write example into

fouter<-function() {     finner<-function()     {         i<<-i+1     }     i<-0     finner()     print(i) } 

but if don't want nest functions way? in case finner heavy , complicated function (which might want move library), , fouter ad-hoc created function defines 1 iterator. have many fouter-class functions in code, nesting them require duplicating finner inside every single little 1 iterator definition.

i suspect solution has environments, don't know how it. can help?

you need access environment associated fouter function--where call finner is. can parent.frame, , can , set variables get , assign:

finner<-function() {   assign("i", get("i", envir=parent.frame()) + 1, envir=parent.frame()) }  fouter<-function() {   i<-0   finner()   print(i) } 

see ?environment , ?parent.frame more info.

but satisfy curiosity! seem agree not idea. manipulating environments , names can complicated, , unless you're doing complex, there's better way.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -