rvariablessubstitution

How to get name of variable in R (substitute)?


I stacked with trying to pass variable through few functions, and on the final function I want to get the name of the original variable. But it seems like substitute function in R looked only in "local" environment, or just for one level up. Well, let me explain it by code:

fun1 <- function (some_variable) {deparse(substitute(some_variable)}
fun2 <- function (var_pass) { fun1 (var_pass) }
my_var <- c(1,2) # I want to get 'my_var' in the end
fun2 (my_var) # > "var_pass"

Well, it seems like we printing the name of variable that only pass to the fun1. Documentation of the substitute tells us, that we can use env argument, to specify where we can look. But by passing .Global or .BaseNamespaceEnv as an argument to substitute I got even more strange results - "some_variable"

I believe that answer is in this function with using env argument, so, could you please explain me how it works and how can I get what I need. Thanks in advance!


Solution

  • I suggest you consider passing optional name value to these functions. I say this because it seems like you really want to use the name as a label for something in the end result; so it's not really the variable itself that matters so much as its name. You could do

    fun1 <- function(some_variable, name = deparse(substitute(some_variable))) {
        name
    }
    fun2 <- function(var_pass, name = deparse(substitute(var_pass))) { 
        fun1(var_pass, name) 
    }
    my_var <- c(1,2)
    
    fun2(my_var)
    # [1] "my_var"
    
    fun1(my_var)
    # [1] "my_var"
    

    This way if you end up having some odd variable name and want to give a better name to a result, you at least have the option. And by default it should do what you want without having to require the name parameter.