Search code examples
rfunctionglobal-variablesvariable-assignment

R: Create a global variable with the name of a function's input


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.


Solution

  • 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