5

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
  • 4
    First of all, don't do it -- messing in a global environment with functions is almost always a bad idea leading to random overwrites, hard to track bugs and overall chaos. Commented Sep 4, 2010 at 8:46

2 Answers 2

7

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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" 

2 Comments

which one is the plyr function?
@Stephen: oh yeah, right. sapply is from the base package - corrected that. the plyr function are always named with one 'p'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.