Pass the "name" of the variable to r

I was wondering if there is a way to pass the "name" of a variable into R. I want to make the following function more general:

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

What I don't want is a function that only works if the variable I want to change is called "a", so I was wondering if I could do something like passing the variable name as an argument, and then invoke the assignment with that name. Something like that:

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

test(a) #!!!!! Here !!!!!
a

Thanks for your help.

+4
source share
2 answers

If you do not want to pass the variable name (as a character), you can use the following trick:

test <- function (varName) {
  assign(deparse(substitute(varName)), "new", envir = .GlobalEnv)
}
+1
source

'a' .

a <- "old"
test <- function (varName) {
   assign(varName, "new", envir = .GlobalEnv)
}
test('a')
a
# [1] "new"

, , , . , , , "R-ish" .

0

All Articles