提取R中函数内定义的对象

时间:2017-04-05 03:00:14

标签: r function

我在R中编写一个函数,我希望能够从函数中调用不同的对象。我有一个我正在谈论的问题的简单例子(显然不是真正的代码)。

example <- function(a,b){
  c <- a+b
  d <- a*b
  e <- a/b
  e
}

a <- 10
b <- 20

output <- example(a,b)
str(output)

output$c

我的目标是在最后一行显示函数中定义的c的值。在此代码中,输出中保存的唯一内容是返回值,例如

我尝试使用&lt;&lt; - 等来改变本地和全局环境。但这并没有解决问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

我们可以在list中返回多个输出,然后提取list元素

example <- function(a,b){
   c <- a+b
   d <- a*b
   e <- a/b
   list(c=c, d= d, e = e)
}

a <- 10
b <- 20

output <- example(a,b)[['c']]
output
#[1] 30

example(a,b)[['d']]
#[1] 200