提取函数结果

时间:2019-01-31 12:21:45

标签: r function

我看过这里,但无法解决我的问题:Extract the results of a function

比方说,我们有这个虚拟函数,它返回用户写的内容,我该如何提取该函数内部的内容。我从诸如机器学习算法中使用的功能中汲取了灵感。例如这种功能:

z<-train(.........)#just an example

从上面我可以提取几个结果,例如z$finalmodel #an example等。怎么做? 这是我的示例函数:

dummy_fun<-function(x,y){
  y<-deparse(substitute(y))
  x<-deparse(substitute(x))
  z<-data.frame(X=x,Y=y)
  q<-print(paste0("You wrote ",x," and ", y))

}
res<-dummy_fun(Hi,There)

dummy_fun包含对象z和q,如何提取它们? 非常感谢!

1 个答案:

答案 0 :(得分:4)

更简单的功能可能是(没有deparse(substitute())

dummy_fun<-function(x,y){
  z<-data.frame(X=x,Y=y)
  q<-paste0("You wrote ",x," and ", y)
  return(list(z = z, q = q))
 }

使用参数调用时:

> dummy_fun(x = 1, y = 2)
$z
  X Y
1 1 2

$q
[1] "You wrote 1 and 2"