【问题标题】:get the name of the output variable in R获取R中输出变量的名称
【发布时间】: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


【解决方案1】:

这里有两个来自 cmets 的解决方法。这首先使用环境通过引用传递。输出变量作为参数提供给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

【讨论】:

    【解决方案2】:

    这并不是我想要的,但这些都是很好的解决方案。我有另一个想法.. 将输出的名称作为参数给出,然后使用“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')
    

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

    非常感谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多