views:

143

answers:

4

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

+2  A: 

Here is something that works for me. However I' m not sure if this is the optimum solution

a <- function(variable) {
print(deparse(substitute(variable)))
my_command <- paste('internala(',substitute(variable),')',sep = '')
eval(parse(text = my_command))
}

internala <- function(variableXX) {
namex=deparse(substitute(variableXX))
print(namex)
}
gd047
Upvote because it seems to does the trick except for two minor quibbles: 1.) you should deparse the substitute, otherwise you'll get an error if you call a(b + 1). 2.) based on maria's comments you'll have to go up parent frames too.
Jonathan Chang
+2  A: 

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")
Marek
+3  A: 

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?

hadley
Definitely; working with string names is much more straight forward.
Shane
A: 

Thank yo guys for all your comments, they were very useful.

Finally i chose to follow hadley & marek's advice and pass names as arguments

(a <- function(variable, vname=deparse(substitute(variable)))),

which made things easier on every level.

I appreciate all the help,

Maria

Maria