Search code examples
rfunctionpipeassignmagrittr

Pipeable assign function for R -- does not assign anything


I have been trying to make a pipeable assign() function for use in loops in conjunction with paste0().

However I cannot get it to actually assign anything, e.g.

assignp <- function(value, x) {
  
assign(x, value)
  
} 

assignp(13, "thirteen")
print(thirteen)

returns:

Error in print(thirteen) : object 'thirteen' not found

There are no error messages, it just doesn't assign the value to the variable name specified.

Can anyone tell me what I'm doing wrong?


Solution

  • By default assign assigns value in it's current scope i.e within the function in this case. Specify envir = parent.frame() in assign.

    assignp <- function(value, x) {
      assign(x, value, envir = parent.frame())
      #You can also use .GlobalEnv to assign to global environment directly.
      #assign(x, value, envir = .GlobalEnv)
    } 
    
    assignp(13, "thirteen")
    thirteen
    
    #[1] 13