I have a function that refreshes the variable passed with a new value from the DB (under certain conditions). If the set of conditions are not met the return value is the variable itself with no change. The condition is not important but the way of passing the variable with quotes on its name is the trouble. Is there a way to pass the argument without quotes.
Consider a toy function ref
below. We need to pass the variable straight as an argument. At the moment this function works only if I pass the name of the variable as a character vector.
abc=55
wxy=44
ref<-function(variable_name=NULL){
if(exists(variable_name))
{
updated_df = switch(variable_name,
"abc"=paste("Variable1:",variable_name,get(variable_name)),
"wxy"=paste("Variable2:",variable_name,get(variable_name)),
"NOT FOUND")
} else stop("passed variable does not exist")
if(updated_df=="NOT FOUND") updated_df = get(variable_name)
updated_df
}
A similar but not same question was here. It does not help.
1) Use deparse(substitute(x))
to get the name. No packages are used.
ref <- function(variable) {
name <- deparse(substitute(variable))
cat("name:", name, "value:", variable, "\n")
}
# test
abc <- 55
ref(abc)
## name: abc value: 55
2) Another possibility is to pass a formula:
ref2 <- function(formula) {
name <- all.vars(formula)[1]
variable <- get(name, environment(formula))
cat("name:", name, "value:", variable, "\n")
}
# test
abc <- 55
ref2(~ abc)
## name: abc value: 55
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With