0

I want to make a function that takes one variable and returns multiple outputs, so that I can use the latter for other purposes beyond the function. Take the simplified version below for example:

user <- function(x){a <- x+1; a <- a+0.1; b <- a*-1}
sum(a,b)

So if I input user(10), a would be 11.1, b would be -11.1, and sum(a,b) would return 0. But currently R is telling me neither object 'a' or object 'b' is found. How can I fix this?

dasf
  • 1,035
  • 9
  • 16
  • 3
    1) You can't without resorting to `assign` but 2) Don't. That isn't really the R way to do it. If you want to return multiple outputs put them into a list and return the list. – Dason Feb 07 '16 at 03:16
  • A stupid question: if my outputs contain both an array and a vector, would a list be the right data structure for them? – dasf Feb 07 '16 at 03:22
  • 1
    @dasf - yes, a list is the right data structure, it can store both arrays and vectors (and any other data structures). – tospig Feb 07 '16 at 03:30
  • Another duplicate (in case you don't like the marked one) [function with multiple outputs](http://stackoverflow.com/q/8216470/903061). – Gregor Thomas Feb 07 '16 at 03:55

1 Answers1

1

It's really very easy. Just return a list:

user <- function(x){a <- x+1; a <- a+0.1; b <- a*-1; return( list(a,b, absum=sum(a,b) )) }

I disagree with Dason at least on my first reading. This is exactly the R-way to do it. On my second reading I think he was trying to get across the notion that functions have environments and that you cannot expect variables to persist outside of them unless they are returned in a defined structure. Lists are the typical structure for returning more complex objects. Might be better to return a named list so that the indexing conventions might be available.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • I think you agree with me. I was saying that direct assigning to 'a' and 'b' from inside the function is not the R way to do it. – Dason Feb 07 '16 at 03:27