Global variable in function R

I created a function to process some of my data, for example:

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

But I do not see a change from the "old" to the "new", I think this is some kind of "global variable", any suggestion?

Thank!

+5
source share
2 answers

for assign(x,value), x should be the name of the variable, not the value, so x should be in the form of the: character assign("a","new"), and for use in your function try:

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

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

> old
[1] "new"
+7
source

you can combine your function with a function sapply, for example:

require (plyr)
b <- sapply (a, test)
b
  old 
"new" 

, a, .

:

a <- c("old", "oold", "ooold", "oooold")
b <- sapply (a, test)
b
   old   oold  ooold oooold 
 "new"  "new"  "new"  "new" 
+2

All Articles