开发者

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)
开发者_StackOverflow中文版} 
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!


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"


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" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜