russellpierce
russellpierce

Reputation: 4711

How to access a variable stored in a function in R

One of the features of R that I've been working with lately (thanks R.cache) is the ability of functions to declare other functions. In particular, when one does this, one is able to have some variables be an inherent part of the resulting function.

For example:

functionBuilder <- function(wordToSay) {
  function() {
    print(wordToSay)
  }
}

Can build a function like so:

functionToRun <- functionBuilder("hello nested world")

Then functionToRun() will result in "hello nested world". But if you just look at functionToRun (i.e., print it), you will see code that matches functionBuilder. What you will also see is that functionToRun has an environment. How can one access the value of wordToSay that is stored inside of functionToRun?

At first I tried: get("wordToSay",env=functionToRun) ... but functionToRun isn't an environment and can't be transformed into an environment via as.environment. Similarly, because functionToRun isn't an environment, you can't attach to it or use with.

Upvotes: 1

Views: 160

Answers (1)

russellpierce
russellpierce

Reputation: 4711

I found that environment was the accessor function to get and set environments, in an analgous way to how names gets and sets name attributes. Therefore, the code to get functionToRun's environment is environment(functionToRun) and therefore, we can access wordToSay with the line get("wordToSay",environment(functionToRun)).

Upvotes: 2

Related Questions