标题不是超级描述性的,因为问题比我能想到的合理标题更长。
我想拥有一个可以从其他函数中获取对象名称的函数,该函数可以用作另一个函数中的参数。这是一个准系统的尝试:
grab <- function(x) {
as.character(substitute(x))
}
FUN <- function(foo, bar = grab(foo)) {
bar
}
FUN(mtcars)
在这里,我想FUN
返回字符串“ mtcars”,但它返回“ foo”。制作获取功能如何做到这一点(我想这样做是因为我将使用它作为txt / csv等文件的默认值。这是一个方便的设置。
这是一些失败的尝试(但是我想拥有一个通用的抓取功能):
FUN2 <- function(foo, bar = as.character(substitute(bar))) {
bar
}
FUN2(mtcars)
#==================
FUN3 <- function(foo, bar) {
if(missing(bar)) bar <- foo
as.character(substitute(bar))
}
FUN3(mtcars)
现实生活中的例子:
real_example <- function(obj, file = grab(obj)) {
write.csv(obj, file = sprintf("%s.csv", file))
}
您可以尝试sys.call
访问父调用:
## "which" is the number of the argument of interest
grab <- function(which) {
## which + 1, because [1] == name of function/call
## and arguments are 2:n
as.character(sys.call(-1L)[which+1L])
}
FUN <- function(foo, bar = grab(1L)) {
bar
}
FUN(mtcars)
# "mtcars"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句