Sunday, 15 September 2013

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


Still trying to enter R logic ... the "best" to open the results (on LHS) What is the way to return a number of values ​​from the function?

I can not do this apparently:

  R> FunctionReturningTwoValues ​​& lt; - Function () {Return (C (1, 2))} R & gt; Returning function value two () [1] 1 2R & gt; A, B & L; - Returning function two values ​​() error: unexpected ',' in 'A,' R & gt; C (a, b) & lt; - functionReturningTwoValues ​​() c (a, b) & lt; Error in functionReturningTwoValues ​​(): Object 'a' not found  

Should I really do the following thing?

  R & gt; R & lt; - Returning function two values ​​() R & gt; A & lt; - r [1]; B & L; - r [2]  

Or will the R programmer write something else:

  R> FunctionReturningTwoValues ​​& lt; - Function () {Return (List (first = 1, seconds = 2))} R & gt; R & lt; - Returning function two values ​​() R & gt; R $ first [1] 1 r & gt; R $ second [1] 2  

--- Edit to answer Shen's questions ---

Let me actually name the parts with the result value Do not need to. I am implementing a composite function for the first component and one second component ( min and max ), if it was the same task for both components, Will not need them).

(1) list [...] & lt; - I had a decade ago posted on it. It does not require a special operator but it is necessary that the list should be written on the left hand side like [...]

  # first run source command Displayed below or installed other and load gsubfn dev pkg (see note) list [a, b]  

Note: Recently list has been added to its development version and it can be obtained through the following:

  source ("https: // Raw.githubusercontent.com/ggrothendieck/gsubfn/ Master/R / list.R ")  

or install and load the gsubfn github development package (using devtools package):

  devtools :: install_github ("Ggrôndndieck / gsubfn") library (GSUBFN)  

If you only need first or second component Also do all the work:

  list [A] & lt; - functionReturningTwoValues ​​() list [A,] & lt; - Function Returning Value () List [, B] & lt; - Return function two values ​​()  
<(> if you only need one value then functionReturningTwoValues ​​() [[1]] or functionReturningTwoValues () [[2]] will suffice.)

See the quoted R-help thread for more examples.

(2) with If the intention is to add multiple values ​​later and return value is named, then with a simple option with :

  myfun & lt; - List of functions (a = 1, b = 2) [a, b]] and  / P> 
  attached (myfun ()) a + b  

Added: with and attached


No comments:

Post a Comment