considerar esta función a()
, que imprime el argumento que se aprobó en:sustituto() para obtener nombres de argumentos, múltiples niveles de hasta
a <- function(x) {
message("The input is ", deparse(substitute(x)))
}
a("foo")
# The input is "foo"
tmplist <- list(x1 = 1, x2=2)
a(tmplist)
# The input is tmplist
que funciona. Pero cuando a()
se llama de otra función, ya no imprime los nombres de los argumentos originales:
b <- function(y) {
a(y)
}
b("foo")
# The input is y
b(tmplist)
# The input is y
Una solución que parece funcionar es para envolver en otro substitute
y un eval
:
a1 <- function(x) {
message("The input is ", deparse(eval(substitute(substitute(x)), parent.frame())))
}
a1("foo")
# The input is "foo"
tmplist <- list(x1 = 1, x2=2)
a1(tmplist)
# The input is tmplist
b1 <- function(y) {
a1(y)
}
b1("foo")
# The input is "foo"
b1(tmplist)
# The input is tmplist
pero esto parece poco elegante. Y falla si agrego otra capa:
c1 <- function(z) {
b1(z)
}
c1("foo")
# The input is z
¿Hay una buena manera general de obtener el argumento original?
No soy un experto en manejo de entornos, pero creo que jugar con 'parent.frame' como lo hizo kohske, o especificar una variable global son sus únicas opciones. R no pasa por referencia como lo hace c. –