1

I'm trying to create a global variable by means of a function in R:

f <- function(name, value) {
  name <<- value
}

if I type the command

f(x,3)

I get a global variable called 'name' with the value 3. However, I want the variable's name to be 'x' instead of 'name'

Does anyone know, how to solve this problem? :)

Edit: This is a stripped down and extremely simplified version of my problem. I know, there is the assign() command or also the '<-'-operator, both doing the same.

4
  • 1
    There is already a built-in R function that does this, assign, where you provide the variable name as a character. No need to write your own function. Also, pay very careful attention to where the assignment takes place via the pos or envir arguments. Commented Nov 6, 2018 at 19:28
  • Thanks for your quick answer @joran, I'm afraid I forgot to mention that this is an extremely simpified version of my problem. I'm aware of the assign()-function, however I'd like to pursue the idea of doing it with a function. Do you know, whether my idea would be theoretically possible? Commented Nov 6, 2018 at 19:45
  • @GalvinHoang It's possible with assign. You can use assign inside a function or outside a function. If you've tried to use assign and found that it's not working. And you've paid attention to joran's whole comment and are being careful about where the assignment takes place, then post your code and we'll help you. Though most everyone on here will try to talk you out of it as it's almost always a Very Bad Idea. Commented Nov 6, 2018 at 19:51
  • If your issue with assign is that you don't want to pass the name as a character string, then you should look up introductory material on Non-Standard Evaluation. The rlang package is the new popular way to do that. Commented Nov 6, 2018 at 19:55

1 Answer 1

4

You can write this function to accept a string and then assign gloablly (standard evaluation). You can also not use a string and just pass in name (non standard evaluation). rlang makes the non-standard evaluation way simple, see below.

install.packages('rlang')    
library(rlang) 

global_assign_se <- function(name, value) {
  assign(name, value, envir = .GlobalEnv)
}
# Here we put quotes around the variable name 
global_assign_se('item_assigned_globally_se', T)
item_assigned_globally_se # true

global_assign_nse <- function(name, value) {
  name <- enquo(name)
  name <- quo_name(name)
  assign(name, value, envir = .GlobalEnv)
}
# Here we don't put quotes around the variable name
global_assign_nse(item_assigned_globally_nse, 'true') 
item_assigned_globally_nse # true
Sign up to request clarification or add additional context in comments.

Comments

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.