[R] Trying to create a function to extract values from a matrix

R. Michael Weylandt michael.weylandt at gmail.com
Thu Oct 27 17:22:52 CEST 2011


This might be an easier method:

suppose your data is in MAT

t(apply(MAT, 1, function(v) eigen(matrix(v, 2))$values))

Your problem is that return() automatically returns the output and
ceases function execution as soon as its hit.

Michael

On Thu, Oct 27, 2011 at 10:44 AM, StephenHughes <kshughes at ncsu.edu> wrote:
> My issue seems simple but I can't find any method to work...
>
> I've got a matrix with 4 columns and I want to extract the values from each
> row to make a new 2x2 matrix for each row.  From these resultant matrices, I
> want to get the Eigen Values and output them from the function as usable
> numbers (not a text string).
>
> Here's the function...
>
> ###
>
> Ef =
> function(MAT) {for(i in c(1:(length(MAT)/4)))
> return(matrix(c (eigen(matrix(c(MAT[i,]),ncol=2))$values),ncol=2))}
>
> ###
>
> This function will return only the Eigen Values of the first row (MAT[1,])
> of the matrix.  However, if I replace "return" in the function with "cat",
> the function will output all the desired values, but they will be as a text
> string, which I can't use.
>
> Furthermore, if I set a variable in the function, and then return the
> variable at the end of the function, it yields the Eigen Values for the last
> row of my matrix.  That function looks like...
>
> ###
>
> Ef=
> function(MAT) {for(i in c(1:(length(MAT)/4)))
> EV=(matrix(c (eigen(matrix(c(MAT[i,]),ncol=2))$values),ncol=2));
> return(EV)}
>
> ###
>
> >From what I can tell, it seems that the function is working, however, I
> don't know how to get it to spit out all the information in a usable manner.
> Thanks for any suggestions.
>
> Stephen
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Trying-to-create-a-function-to-extract-values-from-a-matrix-tp3944737p3944737.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list