mariotomo mariotomo - 1 year ago 61
R Question

Function returning more than one value

still trying to get into the R logic... what is the "best" way to unpack the results from a function returning multiple values?

I can't do this apparently:

R> functionReturningTwoValues <- function() { return(c(1, 2)) }
R> functionReturningTwoValues()
[1] 1 2
R> a, b <- functionReturningTwoValues()
Error: unexpected ',' in "a,"
R> c(a, b) <- functionReturningTwoValues()
Error in c(a, b) <- functionReturningTwoValues() : object 'a' not found

must I really do the following?

R> r <- functionReturningTwoValues()
R> a <- r[1]; b <- r[2]

or would the R programmer write something more like this:

R> functionReturningTwoValues <- function() {return(list(first=1, second=2))}
R> r <- functionReturningTwoValues()
R> r$first
[1] 1
R> r$second
[1] 2

--- edited to answer Shane's questions ---

I don't really need giving names to the result value parts. I am applying one aggregate function to the first component and an other to the second component (
. if it was the same function for both components I would not need splitting them).

Answer Source

(1) list[...]<- I had posted this nearly 10 years ago on r-help. It does not require a special operator but does require that the left hand side be written using list[...] like this:

# run the source command below first
list[a, b] <- functionReturningTwoValues()

Note: Recently list has been added to the development version of the gsubfn package and can be sourced via:


If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

See the cited r-help thread for more examples.

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3) attach Another alternative is attach:

a + b

ADDED: with and attach

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download