[R] accessing return variables from a function

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri Jul 9 12:38:45 CEST 2010


On Fri, Jul 9, 2010 at 10:20 AM, Noah Silverman <noah at smartmediacorp.com> wrote:
> Hi,
>
> I am trying to figure out a "short" way to access two values output from
> the sort function.
>
>>x <- c(3,4,3,6,78,3,1,2)
>>sort(x, index.return=T)
> $x
> [1]  1  2  3  3  3  4  6 78
>
> $ix
> [1] 7 8 1 3 6 2 4 5
>
>
> It would be great to do something like this (doesn't work.):
>
> c(y, indexes) <- sort(x, index.return=T)
>
> But that doesn't work.
>
> I CAN grab the output of sort in a variable and then access it twice to
> get the values, but that seems wasteful.

 Care to do a little study to see how wasteful? The difference is
going to be between:

 foo = sort(...)
 repeat loads of times{
   f(foo$x)
   g(foo$ix)
 }

and

 foo = sort(...)
 x=foo$x
 ix = foo$ix
 repeat loads of times{
    f(x)
    g(ix)
  }

  I'd guess that for most applications the difference is less than
something very close to zero.

Barry



More information about the R-help mailing list