简体   繁体   中英

R nonstandard evaluation: pass the name of a variable as a parameter to a function and have the function assign a value to it

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM