[英]Returning objects from functions (R)
I don't understand why this snippet does not work. 我不明白为什么此代码段不起作用。 My understanding of the function
return()
is that it enables you to use an object that was created inside a function outside the function. 我对函数
return()
理解是,它使您可以使用在函数外部的函数内部创建的对象。
I have this simple function and I want to use product
outside of my function. 我有这个简单的功能,我想在功能之外使用
product
。 How can I do this? 我怎样才能做到这一点? Or, alternatively, have I entirely missed the point of the
return()
function? 或者,或者,我是否完全错过了
return()
函数的要点?
simple_fcn<- function(input1, input2)
{
product = input1*input2
return(product)
}
simple_fcn(2,5)
print(product)
You need to save the return argument when calling the function into a variable that is available in the global environment, ie try the following: 在将函数调用到全局环境中可用的变量时,需要保存return参数,即尝试以下操作:
product_global <- simple_fcn(2, 5)
print(product_global)
In addition to Felipe's comment, to assign product
to a variable in a function's parent environment you can do product <<- product
or assign('product', product, 1)
inside the function. 除了Felipe的注释,要将
product
分配给函数的父环境中的变量,您可以在函数内部执行product <<- product
或assign('product', product, 1)
。 For more flexible assignments see ?assign
. 有关更灵活的分配,请参见
?assign
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.