开发者

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(var开发者_如何学CiableXX) {

    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


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?


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")


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)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜