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!
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.
Global variables can be used by everyone, both inside of functions and outside.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With