0

I am certain this is answered somewhere, but was unable to find it. Programming with dplyr also doesn't give the answer.

I need to pass the name of a variable as a parameter to a function and have the function assign a value to it.

assign_x <- function(xf = x){
  xf <- 5
}
rm(x)
assign_x(x)
x

Use Case:

I want to write a wrapper to odbc::dbConnect where I check to see if the connection is already valid and recycle the connection if needed. Sometimes I need to disconnect then reconnect to get the connection to work properly if the query hangs on me.

Harlan Nelson
  • 1,394
  • 1
  • 10
  • 22
  • 1
    `x` is local, maybe assign it to `.Globalenv`? I naively cannot see how you can get local `x` by simply calling `assign_x`. – NelsonGon Sep 26 '19 at 16:41
  • 1
    This is probably not what you need but try it `assign_x <- function(xf = x){ xf <- 5 x <- deparse(substitute(x)) assign(x,xf,envir = .GlobalEnv) }`. It doesn't make sense to define `assign_x` that uses `assign`(frowned upon) anyways.. – NelsonGon Sep 26 '19 at 16:45

1 Answers1

1

Use parent.frame() to assign in, well, the caller's environment.

assign_x <- function(xf = 'x', value = 5){
  x <- deparse(substitute(xf))
  assign(x, value, envir = parent.frame())
}

rm(x)

Warning message:
In rm(x) : object 'x' not found

assign_x(x)
x
#[1] 5

assign_x(y, pi)
y
#[1] 3.141593
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • That answer works. After researching: assign_x <-function(value = 5){value} x <-assign() would be better. But I am trying to run dbConnect in Rstudio and the "Connections" panel tab doesn't show a connection unless it is run in the global environment. – Harlan Nelson Sep 26 '19 at 19:39