# Re: [R] creating matrices from vectors

From: Erik Iverson <iverson_at_biostat.wisc.edu>
Date: Sat, 15 Nov 2008 10:56:09 -0600

James Rudge wrote:
> If I have 4 vectors (a, b, c, and d) each of length 1000, how do I then create 1000 two by two matrices from these vectors, such that:
>
> myMatrix[i] = matrix(c(a[i],b[i],c[i],d[i]),2)
>
> Then I'd like to create a single vector containing the largest eigenvalues of each matrix?
>
> (Sorry I am quite new to R)
> Many thanks,
> James

Something like this might get you started:

## use mapply to construct the matrices, returns list of matrices m1 <- mapply(function(...) matrix(as.numeric(list(...)), nrow = 2,

byrow = TRUE), a, b, c, d, SIMPLIFY = FALSE)

## apply the eigen function to the list
m2 <- lapply(m1, eigen, only.values = TRUE)

## the largest eigenvalue is in the first slot sapply(sapply(m2, "[", "values"), "[", 1)

Where a, b, c, d are your vectors. I tried this on a small example, with vectors of length 10, seemed to work. In general, watch for naming objects 'c', as that is the name of an important built-in R function.

The apply functions can help a lot in cases like these, see their respective help pages.

Hope this helps,
Erik

>
> _________________________________________________________________
> [[elided Hotmail spam]]
>
> ______________________________________________
> 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.

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. Received on Sat 15 Nov 2008 - 16:56:57 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 15 Nov 2008 - 17:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.