在R中获取输出变量的名称

抱歉我的英语不好

在R中是否有一种方法可以将函数的名称用于函数的返回值,就像使用“substitute”来捕获输入变量的名称一样.我的意思是像这个“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

解决方法1

myFun1 <- function(x, output){
  nameIN=substitute(x)
  nameOUT=substitute(output)
  output$value=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(output$value)
}

myOUTPUT <- new.env()
myOUTPUT$value <- 1
myFun1(myINPUT, myOUTPUT)
# 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$value
# [1] 24

解决方法2

@Roland建议(至少我对他的评论的解释):

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
点赞