Is there a way to output e.g. 2 objects without using list()
?
my.fun=function(vector, index)
{
a=fun.a(vector, index)
b=fun.b(vector, index)
output=list(a,b)
}
Or to output 2 lists of objects? Considering that I could also have:
c=fun.a(vector, index)
d=fun.b(vector, index)
And wanted list(a,b)
and another list(c,d)
for the same function.
This is just a small example for what I am looking for, my function is applied to large objects and I export them as a list, however I would like to export also an intermidiate calculation. One option would be to merge all in the same list, but I would like to know if there is another solution to this.
It is important to note that when one says multiple outputs, it is not that there are several alternative outputs, there is a set or ordered sequence of outputs. You can view the output as a single sequence or as several numbers. When you talk of multiple outputs you are viewing it as several numbers.
Multiple-number outputA multivariable function is just a function whose input and/or output is made up of multiple numbers. In contrast, a function with single-number inputs and a single-number outputs is called a single-variable function.
1 Answer. In R programming, functions do not return multiple values, however, you can create a list that contains multiple objects that you want a function to return.
You can only return
one object in a function. But you have some other options. You could assign intermediate objects to the global environment (you need to be careful not to overwrite anything) or you could pass an environment to your function and assign objects to it.
Here's an example of the latter suggestion:
fun <- function(x, env) {
env$x2 <- x^2
x^3
}
set.seed(21)
x <- rnorm(10)
myEnv <- new.env()
fun(x, myEnv)
# [1] 4.987021e-01 1.424421e-01 5.324742e+00 -2.054855e+00 1.061014e+01
# [6] 8.125632e-02 -3.871369e+00 -8.171530e-01 2.559674e-04 -1.370917e-08
myEnv$x2
# [1] 6.288699e-01 2.727464e-01 3.049292e+00 1.616296e+00 4.828521e+00
# [6] 1.876023e-01 2.465527e+00 8.740486e-01 4.031405e-03 5.728058e-06
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With