【问题标题】:do.call cbind and sapply in R在 R 中调用 cbind 和 sapply
【发布时间】:2013-02-02 11:12:32
【问题描述】:

我有一个给定矩阵的列之间所有可能组合的列表。我想计算每个组合的 cov,最后计算每个协方差矩阵的行列式。

问题是我需要在计算行列式之前计算一个平方矩阵,我尝试将 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)

【问题讨论】:

  • 不应该是sapply(list.of.cov.matrices.2, det)吗?
  • @plannapus 谢谢,但不幸的是列表不是平方矩阵,我认为这是问题所在。
  • 当我使用您的代码但将最后一行替换为list.of.det&lt;-sapply(list.of.cov.matrices.2,det) 时,它可以工作。 list.of.matrices不是由方阵组成,但list.of.cov.matrices.2是。

标签: r


【解决方案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

它们都应该给出相同的结果,但顶部的结果会明显更快并且输入更少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多