nopeva
nopeva

Reputation: 1605

do.call cbind and sapply in R

I have a list of all possible combinations between the columns of a given matrix. I would like to compute the cov of each combination and finally the determinant of each covariance matrix.

The problem is that I need to compute a squared matrix before calculating the determinant, I tried to use do.call with cbind and sapply all together but does not work:

matrices.sq=do.call("cbind",lapply(list.of.matrices,get))

The code is the following:

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)
list.of.cov.matrices.2=list.of.cov.matrices[-(1:ncol(myarray))] #so get those with more than one column
list.of.det<- sapply(list.of.cov.matrices.2, det)

Upvotes: 2

Views: 2496

Answers (1)

flodel
flodel

Reputation: 89107

I don't think you need to store all those matrices. First, compute your covariance matrix, then use the same apply call you have to create sub-matrices but instead of storing them just compute their determinant:

cov.mat <- cov(myarray)
# is a 5-by-5 matrix

dets <- apply(expand.grid(rep(list(c(FALSE, TRUE)), ncol(cov.mat))),
              1, function(j) det(cov.mat[j, j, drop = FALSE]))
# is a vector of length 32

But if you really have to do it the long way:

list.of.cov.mat <- apply(expand.grid(rep(list(c(FALSE, TRUE)), ncol(cov.mat))),
                         1, function(j) cov.mat[j, j, drop = FALSE])
# is a list of 32 covariance matrices
dets <- sapply(list.of.cov.mat, det)
# is a vector of length 32

Or the super long way:

list.of.mat <- apply(expand.grid(rep(list(c(FALSE, TRUE)), ncol(cov.mat))),
                         1, function(j) myarray[, j, drop = FALSE])
# is a list of 32 matrices
list.of.cov.mat <- lapply(list.of.mat, cov)
# is a list of 32 covariance matrices
dets <- sapply(list.of.cov.mat, det)
# is a vector of length 32

They should all give the same result but the one at the top will be significantly faster and less typing.

Upvotes: 1

Related Questions