2014-06-26 70 views
3

对不起我的英文不好得到R中的输出变量的

是否有R A的方式获得用于函数内的一个函数的返回值的名称,以同样的方式,你可以赶上名称输入变量名称为“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 

我一直在寻找一个答案,我要疯了。这似乎很简单,但我 找不到任何东西。

谢谢

+1

这是不可能的,至少不是所谓的函数。 – gagolews

+0

你不能这样做。接下来最好的事情是将myOUTPUT作为参数传递给myFun,并使用替代品来获取其名称。 –

+1

你可以使用'assign'而不是'='或'<-'吗?与其命名参数的基元相反。 – Roland

回答

2

以下是来自评论的两种解决方法。这首先使用环境通过引用传递。输出变量作为参数提供给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 
0

这不是确切地说,我一直在寻找,但这些都是很好的解决方案。我有另一个想法..给输出的名称作为参数,然后,分配值给它“分配(outPUT_name,出,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') 

可能是我有点任性,但我想不会有输出名称添加作为参数......这是一个耻辱没有办法来实现这一点

非常感谢你