Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing an argument without quotes to an R function using its name in a switch statement

Tags:

r

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.

like image 474
Lazarus Thurston Avatar asked Dec 06 '22 12:12

Lazarus Thurston


1 Answers

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 
like image 183
G. Grothendieck Avatar answered Jun 06 '23 14:06

G. Grothendieck