ben_aaron
ben_aaron

Reputation: 1532

Retrieve/access dynamic variable from R function

I have a function in R that structures my raw data. I create a dataframe called output and then want to make a dynamic variable name depending on the function value block.

The output object does contain a dataframe as I want, and to rename it dynamically, at the end of the function I do this (within the function):

a = assign(paste("output", block, sep=""), output)

... but after running the function there is no object output1 (if block = 1). I simply cannot retrieve the output object, neither merely output nor the dynamic output1 version.

I tried this then:

a = assign(paste("output", block, sep=""), output) return(a)

... but still - no success. How can I retrieve the dynamic output variable? Where is my mistake?

Upvotes: 1

Views: 1687

Answers (1)

Jeff Allen
Jeff Allen

Reputation: 17527

Environments.

assign will by default create a variable in the environment in which it's called. Read about environments here: http://adv-r.had.co.nz/Environments.html

I assume you're doing something like:

foo <- function(x){ assign("b", x); b}

If you run foo(5), you'll see it returns 5 as expected (implying that b was created successfully somewhere), but b won't exist in your current environment.

If, however, you do something like this

foo <- function(x){ assign("b", x, envir=parent.frame()); b}

Here, you're assigning not to the current environment at the time assign is called (which happens to be foo's environment). Instead, you're assigning into the parent environment (which, since you're calling this function directly, will be your environment).

All this complexity should reveal to you that this will be fairly complex, a nightmare to maintain, and a really bad idea from a maintenance perspective. You'd surely be better off with something like:

foo <- function(x) { return(x) };
b <- foo(5)

Or if you need multiple items returned:

foo <- function(x) { return(list(df=data.frame(col1=x), b=x)) }
results <- foo(5)
df <- results$df
b <- results$b

But ours is not to reason why...

Upvotes: 6

Related Questions