Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 514
EvilAnton Avatar asked Jun 19 '14 15:06

EvilAnton


People also ask

How do I find the name of a variable in R?

You can use ls() to list all variables that are created in the environment. Use ls() to display all variables.

How do I convert a string to a variable name in R?

We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function. Parameter: variable_name is the name of the value.

What is R variable?

In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object assigned to it. So R is called a dynamically typed language, which means that we can change a variable's data type of the same variable again and again when using it in a program.


1 Answers

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 what 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.

like image 57
MrFlick Avatar answered Oct 04 '22 01:10

MrFlick