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.
I have this simple function and I want to use product
outside of my function. How can I do this? Or, alternatively, have I entirely missed the point of the return()
function?
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:
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. For more flexible assignments see ?assign
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.