获取R中输出变量的名称

获取R中输出变量的名称,r,R,对不起,我的英语很差 在R中是否有一种方法可以获取用于函数内函数返回值的名称,就像您可以用“替换”捕捉输入变量的名称一样??。我的意思是类似“outputname”函数的东西: 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)

对不起,我的英语很差

在R中是否有一种方法可以获取用于函数内函数返回值的名称,就像您可以用“替换”捕捉输入变量的名称一样??。我的意思是类似“outputname”函数的东西:

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
我一直在寻找答案,我快疯了。看起来很简单,但我 什么也找不到


谢谢

以下是评论中的两个解决方法。这首先使用环境通过引用传递。输出变量作为参数提供给
myFun1
。第二种方法使用
assign
myFun2
的返回值分配给输出变量,并通过检查调用堆栈来检索输出变量的名称

myINPUT <- 12

这并不是我想要的,但这些都是很好的解决方案。我有另一个主意。。以参数形式给出输出的名称,然后使用“assign(output_name,out,envir=parent.frame()”)为其赋值

然后你可以这样使用它:

myFun(myINPUT,'myOUTPUT')
也许我有点任性,但我不想把输出名称作为参数添加进去。。。真遗憾,没有办法做到这一点


非常感谢

这是不可能的,至少在调用的函数中是不可能的。您不能这样做。下一个最好的方法是通过引用将myOUTPUT作为参数传递给myFun,并使用substitute来获取其名称。您是否可以使用
assign
而不是
=
谢谢。我会尝试“参考”和“指派”建议。@ GPF考虑罗兰的建议。如果您使用
assign
,则在
myFun
内部,您可以调用
sys.calls
来访问父调用并提取要分配给的变量的名称。
myFun2=function(x){
  nameIN=substitute(x)
  nameOUT=as.list(sys.calls()[[1]])[[2]]
  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)
}

assign('myOUTPUT', myFun2(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
myFun=function(x,outPUT_name){
  nameIN=substitute(x)
  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 ", outPUT_name, "and this is the value:\n")
  print(out)
  assign(outPUT_name,out,envir=parent.frame())
}
myFun(myINPUT,'myOUTPUT')