Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variable in R function

I created a function for processing some of my data, like this:

a <- "old" 
test <- function (x) {
   assign(x, "new", envir = .GlobalEnv)
} 
test(a)

But I can't see the a change from "old" to "new", I guess this is some of the "global variable", any suggestion?

Thanks!

like image 243
lokheart Avatar asked Sep 04 '10 04:09

lokheart


People also ask

Can R function access global variable?

Overview. Global variables in R are variables created outside a given function. A global variable can also be used both inside and outside a function.

Can you use global variables in a function?

Global variables can be used by everyone, both inside of functions and outside.

How do I show global environment in R?

The top level environment available to us at the R command prompt is the global environment called R_GlobalEnv . Global environment can be referred to as . GlobalEnv in R codes as well. We can use the ls() function to show what variables and functions are defined in the current environment.


1 Answers

for assign(x,value),x need to be a name of a variable not value of it, so x should be in character form: assign("a","new"),and in order to be used in your function,try:

test <- function (x) 
{
  assign(deparse(substitute(x)), "new", envir = .GlobalEnv)
} 

in your case, you will creat a variable named "old" and assign "new" to it:

> old
[1] "new"
like image 112
alan Avatar answered Sep 29 '22 12:09

alan