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
You can use ls() to list all variables that are created in the environment.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With