4

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

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 can do something like passing the variable name as an argument and then call the assign function with that name. Something like this:

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

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

Thanks for your help.

10
  • Do you mean this - test(varName = 'a') ? Commented Sep 26, 2013 at 16:48
  • 2
    You want to reassign the value of a from old to new or you want to assign the value of new to a new variable old (if its the latter, your function does that, the former is what <- is for...)? Also, if you find yourself using assign you're almost always doing it wrong. Commented Sep 26, 2013 at 16:48
  • Actually what I really want to do is pass to a function a variable from a environment without assigning the environment to the function itself. Something like myFunction(e1$myVar) where the function myfunction(theVar) does an assignment to "theVar" and it modifies myVar. But I can't get it to work. Commented Sep 26, 2013 at 17:16
  • I still don't understand at all what you're hoping for. Please edit you question to include desired inputs and outputs as well as a description of the larger problem you're looking to solve. I have a feeling that there is a much better option than dealing with assign and passing environments around... Commented Sep 26, 2013 at 17:20
  • 1
    @Justin I think he's looking for a modification of assign that takes a variable, not a character. Put another way, I think he's looking for a variation of <- that takes an environment argument. Commented Sep 26, 2013 at 17:30

2 Answers 2

1

If you don't want to pass variable name (as character) you can use following trick:

test <- function (varName) {
  assign(deparse(substitute(varName)), "new", envir = .GlobalEnv)
}
Sign up to request clarification or add additional context in comments.

Comments

0

Passing the string 'a' to your function will work.

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

However, as I said in my comments, I don't think this is the correct solution to your problem. If you want to ask a more general question about the thing you're trying to do, I bet there is a more "R-ish" solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.