Define global variable using function argument in R

19,849

Use the assign() function.

  assign("new.data", my.data[,-col], envir = .GlobalEnv) 

The first argument should be a string. In this case, the resultant global variable will be named "new.data". If new.data is the name itself, drop the quotes from the function call.

<<- does not always assign to the global environment.

In general, however, it is better to return things from a function than set global variables from inside a function. The latter is a lot harder to debug.

Share:
19,849
cerpintaxt
Author by

cerpintaxt

I'm a Data Scientist at Twitch. I work primarily in R, SQL, and Python

Updated on June 12, 2022

Comments

  • cerpintaxt
    cerpintaxt almost 2 years

    I'm trying to write a function in R that drops columns from a data frame and returns the new data with a name specified as an argument of the function:

    drop <- function(my.data,col,new.data) {
    new.data <<- my.data[,-col] 
    return(new.data)
    }
    

    So in the above example, I want a new data frame to exist after the function is called that is named whatever the user inputs as the third argument.

    When I call the function the correct data frame is returned, but then if I then try to use the new data frame in the global environment I get object not found. I thought by using the <<- operator I was defining new.data globally.

    Can someone help me understand what's going on and if there is a way to accomplish this?

    I found this and this that seemed related, but neither quite answered my question.

  • cerpintaxt
    cerpintaxt about 10 years
    Thanks this is helpful. I'll live with slightly more typing and just use return.
  • Christopher Louden
    Christopher Louden about 10 years
    @JakeBurkhead: I expanded to explain when to quote and when not to.
  • algae
    algae about 4 years
    Is there a systematic way to do this for a pile of variables?