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

时间:2014-06-26 14:51:35

标签: 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)
  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

我一直在寻找答案而且我会发疯。这似乎很简单,但我 无法找到任何东西。

由于

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这不是我想要的,但这些都是很好的解决方案。我有另一个想法..将输出的名称作为参数,然后,使用“assign(outPUT_name,out,envir = parent.frame())”为其分配值。

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')

可能是我有点反复无常,但我不想将输出名称添加为参数......很遗憾没有办法实现这一点

非常感谢