2013-02-02 105 views
2

我有列表中给定矩阵的列之间的所有可能的组合。我想计算每个组合的cov并最终计算每个协方差矩阵的行列式。do.call cbind和sapply在R

的问题是,我需要计算行列式之前计算平方矩阵,我试图用do.call与cbind和sapply都在一起,但不工作:

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

的代码如下:

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) 
+0

不应该是'sapply(list.of.cov.matrices.2,det)'? – plannapus

+0

@plannapus谢谢,但不幸的是一个列表不是一个平方矩阵我认为这是问题。 – nopeva

+0

当我使用你的代码,但用'list.of.det <-sapply(list.of.cov.matrices.2,det)'替换最后一行时,它可以工作。 'list.of.matrices'不是由平方矩阵组成,而是'list.of.cov.matrices.2'。 – plannapus

回答

1

我不认为你需要存储所有这些矩阵。首先,计算你的协方差矩阵,然后用同样的apply叫你必须创建子矩阵,但它不是用来存放他们只计算其决定因素:

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 

但如果你真的有这样做的很长的路要走:

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 

或者超级长的路要走:

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 

他们都应该给予同样的结果,但一个在顶部将更快,更打字是显著。

+0

再次感谢您的帮助 – nopeva