views:

121

answers:

2

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!

+1  A: 

you could combine your function with the sapply function, eg:

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

that way you are applying your function to the actual elements of your a vector - as romunov pointed out in his answer.

another eg:

a <- c("old", "oold", "ooold", "oooold")
b <- sapply (a, test)
b
   old   oold  ooold oooold 
 "new"  "new"  "new"  "new" 
mropa
which one is the plyr function?
Stephen
@Stephen: oh yeah, right. `sapply` is from the base package - corrected that. the plyr function are always named with one 'p'.
mropa
+4  A: 

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"
alan
or just a `test("a")` with original code.
Marek