nopeva
nopeva

Reputation: 1605

get eigenvalues only using sapply in R

I've tried many different things to get the eigenvalues only when looping through the list but did'nt work. That's the code:

myarray=matrix(rexp(200),50,5)
list.of.matrices <- apply(expand.grid(rep(list(c(FALSE, TRUE)), ncol(myarray))),
                              1, function(j)myarray[, j, drop = FALSE])
list.of.cov.matrices=sapply(list.of.matrices, cov)
eigen.val<- sapply(list.of.cov.matrices, eigen$values)

Also tried:

eigen.val=apply(list.of.cov.matrices, 1, function(eigen) FUN(eigen, only.values = T))

Finally I would like to construct a table with the eigenvalues for each matrix.

To build the table I use:

eigen.sum=data.frame(
  list.eigen.of.cor.matrices=rep(1:length( eigen.val), sapply( eigen.val, length)),
  y=unlist( eigen.val)

This does the table but then additional manipulation in excel must follow so would like to do it straight forward if possible.

Upvotes: 2

Views: 217

Answers (1)

Arun
Arun

Reputation: 118889

There are two problems here. First, you have a 0*0 matrix in your input, for which it returns an error. Second, the way you call the eigen function (in the first command) is not correct.

Basically, you'll have to check if the dimension of matrix is NOT 0*0 and then call the eigen function correctly. Try this:

eigen <- sapply(list.of.cov.matrices, function(x) {
    if (prod(dim(x)) > 0) {
        eigen(x)$values
    }
})

Upvotes: 2

Related Questions