0

I am new to R and mostly working with old code written by someone else. And I am trying to create my own R functions.

I found some of the following code used for eigenvalue decomposition.

eigenMatrix = eigen(myMatrix)[[2]]
eigenVals = eigen(myMatrix)[[1]]

Here there is single function that can output 2 different data structures, being, a vector and a matrix depending of the value in the brackets.

When I search of functions with multiple outputs, they usually use lists to output multiple variables at once which does not work, possibly because of different types.

I don't understand why there are two setts of brackets and how the underlying function would work.

Thomas
  • 43,637
  • 12
  • 109
  • 140
MichaelE
  • 763
  • 8
  • 22
  • You should read up on lists in R. Basically using the double bracket ensures that you get the inherent type back. When using only one sets of brackets you get a list no matter the underlying structure. – Dr. Mike Mar 10 '15 at 20:39
  • Thanks, most posts I found just confused me, until I found the this http://stackoverflow.com/questions/2050790/how-to-correctly-use-lists-in-r which specifically explains the double bracket which returns the exact value of the list. By the way what should I do with the question now that I understand the answer? – MichaelE Mar 10 '15 at 20:56
  • Also, is there a performance penalty of calling eigen twice a in the sample code? – MichaelE Mar 10 '15 at 21:06
  • Yes there is because it runs the function twice. myList = eigen(myMatrix) and then eigenMatrix = emyList[[2]], eigenVals = emyList[[1]] runs faster. As it gets the result list and gets the values. Thanks. – MichaelE Mar 10 '15 at 21:17
  • If you found an answer you like you should write the answer here and pick your own answer as the solution such that people can understand what the answer is. – Dr. Mike Mar 11 '15 at 07:06

1 Answers1

0

The posted code takes the eigen function, which returns a list with 2 values. Then the [[]] are use to extract the first and second items from the list. The [[]] is needed to return the underlying structure, and is better explained here: How to Correctly Use Lists in R?

Also, since the eigen function is run twice the code in the question is inefficient.

resultList = eigen(myMatrix)
eigenMatrix = resultList[[2]]
eigenVals = resultList[[1]]

This code is better since eigen is run only once and saves the result of the function as a list and then reads the values from the list.

For the function itself can be coaded as any function with multiple outputs such as here: https://stat.ethz.ch/pipermail/r-help/2007-March/126851.html or here: How to assign from a function with multiple outputs?

The list values can hold any structure and [[]] can be used to return the underlying structure of each value.

Community
  • 1
  • 1
MichaelE
  • 763
  • 8
  • 22