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

5

非常抱歉我的英语不好

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

This is what I wish:

> 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

我一直在寻找答案,但我快要疯了。看起来是件很简单的事情,但我却找不到任何东西。

谢谢。


1
这是不可能的,至少在所调用的函数内部不可能。 - gagolews
1
你能否使用assign代替=<-?与原始操作符不同,它具有命名参数。 - Roland
谢谢。我会尝试“按引用传递”和“赋值”的建议。 - gpf
我还没有学会使用magrittr管道工具,但是难道没有一些管道工具可以获取上一个语句的结果吗?如果是这样的话,您可能可以通过“向后查看”的管道命令来检索。 - Carl Witthoft
顺便提一下,输出对象直到函数完成后才存在。也就是说,在 foo<-bar(x) 中,只有在 return 调用时才会创建 foo。您可以通过以下方式进行验证:xfoo<-function(x) {print(ls(pat='xjk',env=.GlobalEnv));return(x)} 然后跟随 xjk<-xfoo('something') - Carl Witthoft
显示剩余2条评论
2个回答

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

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

也许我有点任性,但我不想将输出名称作为参数添加...很遗憾没有办法实现这一点

非常感谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接