nopeva
nopeva

Reputation: 1605

generate all possible column combinations and create one matrix for each of them in R

I have a matrix like this one:

myarray=cov(matrix(rexp(200),50,10))

I would like to generate all possible combinations of columns and compute the correlation matrix for each combination, if possible, using column numbers instead of names. In a second step I would like to compute the determinant of each matrix so maybe there is an efficient way to do it.

Upvotes: 1

Views: 1060

Answers (1)

flodel
flodel

Reputation: 89057

Here is one way:

list.of.matrices <- apply(expand.grid(rep(list(c(FALSE, TRUE)), ncol(myarray))),
                          1, function(j)myarray[, j, drop = FALSE])

length(list.of.matrices)
# [1] 1024

Then do something like:

result <- sapply(list.of.matrices, function_of_your_choice)

but note that det can only be applied to square matrices... Please clarify.

Upvotes: 2

Related Questions