【发布时间】:2014-06-26 14:51:34
【问题描述】:
对不起我的英语不好
R 中有没有办法在函数中获取用于函数返回值的名称,就像你可以用“substitute”捕获输入变量的名称一样??我的意思是这样的“输出名称”函数:
myFun=function(x){
nameIN=substitute(x)
nameOUT=outputname()
out=x*2
cat("The name of the input is ", nameIN," and this is the value:\n")
print(x)
cat("The name of the output is ", nameOUT, "and this is the value:\n")
print(out)
return(out)
}
这是我希望的:
> myINPUT=12;
> myOUTPUT=myFun(myINPUT)
The name of the input is myINPUT and this is the value:
[1] 12
The name of the output is myOUTPUT and this is the value:
[1] 24
> myOUTPUT
[1] 24
我一直在寻找答案,我快疯了。这似乎很简单,但我 什么都找不到。
谢谢
【问题讨论】:
-
这是不可能的,至少在被调用的函数内是不可能的。
-
你不能这样做。下一个最好的方法是通过引用将 myOUTPUT 作为参数传递给 myFun 并使用替换来获取其名称。
-
你能用
assign代替=或<-吗?与它具有命名参数的原语相比。 -
谢谢。我会尝试“通过引用”和“分配”建议。
-
@gpf 考虑@Roland 的建议。如果您使用
assign,在myFun内,您可以调用sys.calls来访问父调用并提取您要分配的变量的名称。
标签: r