How to assign from a function which returns more than one value?

Still trying to get into the R logic… what is the “best” way to unpack (on LHS) 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 (min and max. if it was the same function for both components I would not need splitting them).

15 Answers
15

Leave a Comment