[R] Function assignment

MacQueen, Don macqueen1 at llnl.gov
Sat Jul 26 21:25:14 CEST 2014

Here is one way:

foo <- function(tmp) assign( tmp, tmp , '.GlobalEnv')

> foo('ick')
> ick
[1] "ick"

Note that you must only use it with a character argument:
> foo(1)
Error in assign(tmp, tmp, ".GlobalEnv") : invalid first argument

Be warned also that assign() should be used very carefully, because it is
easy to unintentionally overwrite objects with it:

> bah <- 3
> bah       
[1] 3
> foo('bah')
> bah
[1] "bah"

Your original bah is gone.

As Jeff suggested, there may be a better way to achieve the same purpose,
whatever that purpose might be. (I hope this wasn¹t homework.)


Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 7/26/14, 5:29 AM, "Florian Ryan" <florian.ryan at aim.com> wrote:

>I would like to use the variable name which i assign the return value
>of a function in a function. Is that possible?
>foo <- function(){
>    some not to me known R magic
>myVariableName <- foo()
>[1] "myVariableName"
>Hope someone can help me.
>	[[alternative HTML version deleted]]
>R-help at r-project.org mailing list
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list