Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one extract the name of a variable in a function that is called from another function in R?

My question is how to extract the name of a variable from a function that is called in another function in R?

To illustrate, here is an example:

a <- function(variable) {

    print(deparse(substitute(variable)))

    internala(substitute(variable))

}

internala <- function(variableXX) {

    namex=deparse(substitute(variableXX))

    print(namex)
}

Calling the function a gives the following result:

>a(whatever)

[1] "whatever"

[1] "substitute(variable)"

which means that i can extract the name of the variable whatever from a, but not from internala.

Any thoughts on this?

Any help will be appreciated!

Maria

like image 953
Maria Avatar asked Feb 22 '10 09:02

Maria


People also ask

How do I get the variable names in R?

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

How do I find the name of an object in R?

names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object.


2 Answers

You're better off not messing around with substitute and friends - you are likely to create a function that will be very hard to program against. Why not just pass in the name of the variable explicitly as a string?

like image 119
hadley Avatar answered Sep 27 '22 22:09

hadley


You could change a function to substitute argument of an internala function and eval it:

a <- function(variable) {
    print(deparse(substitute(variable)))
    eval(substitute(internala(variable))) # this is only change
}

internala <- function(variableXX) {
    namex=deparse(substitute(variableXX))
    print(namex)
}

a(whatever)

As hadley suggest its better to directly pass names. I usually do something like that:

a <- function(variable, vname=deparse(substitute(variable))) {
    print(vname)
    internala(variable, vname)
}

internala <- function(variableXX, namex=deparse(substitute(variableXX))) {
    print(namex)
}

a(whatever)

Each function could be call without passing name, but you can override it. For example:

a(whatever, "othername")
like image 40
Marek Avatar answered Sep 27 '22 21:09

Marek