as.matrix(A$mat) 对于给定列表 A

as.matrix(A$mat) for a given list A

我有 n 个矩阵,我正尝试从 Matrix 包中应用 nearPD()。 我使用以下代码完成了此操作:

A<-lapply(b, nearPD)

其中 b 是 n 个矩阵的列表。

我现在想将列表 A 转换为矩阵。对于单个矩阵,我将使用以下代码:

A<-matrix(runif(n*n),ncol = n) 
PD_mat_A<-nearPD(A)
B<-as.matrix(PD_mat_A$mat)

但我正在尝试使用列表来做到这一点。我尝试了以下代码,但它似乎不起作用:

d<-lapply(c, as.matrix($mat))

如有任何帮助,我们将不胜感激。谢谢。

这是一段代码,您可以尝试重现此代码:

    n<-10
    generate<-function (n){
      matrix(runif(10*10),ncol = 10) 
    }
    b<-lapply(1:n, generate)

这是使用 as.matrix 的最简单方法,正如@nicola 在下面的评论中所指出的,以及(使用 apply 的版本)在上面的评论中由 @cimentadaj 指出:

d <- lapply(A, function(i) as.matrix(i$mat))

我最初的答案是利用 nearPD 数据结构

稍微摆弄一下 nearPD 对象类型,这里是一个提取方法:

d <- lapply(A, function(i) matrix(i$mat@x, ncol=i$mat@Dim[2]))

下面是一些关于我如何得出答案的评论。

这个对象相当复杂,因为 str(A[[1]]) returns

List of 7
$ mat :Formal class 'dpoMatrix' [package "Matrix"] with 5 slots
.. ..@ x : num [1:100] 0.652 0.477 0.447 0.464 0.568 ...
.. ..@ Dim : int [1:2] 10 10
.. ..@ Dimnames:List of 2
.. .. ..$ : NULL
.. .. ..$ : NULL
.. ..@ uplo : chr "U"
.. ..@ factors : list()
$ eigenvalues: num [1:10] 4.817 0.858 0.603 0.214 0.15 ...
$ corr : logi FALSE
$ normF : num 1.63
$ iterations : num 2
$ rel.tol : num 0
$ converged : logi TRUE
- attr(*, "class")= chr "nearPD"

您对 $mat 访问的 "mat" 感兴趣。 @ 符号表明 "mat" 是一个 s4 对象,其组件使用 @ 访问。感兴趣的组件是 "x"、矩阵内容和矩阵的维度 "Dim"。上面的代码将这些信息放在一起,以从 "nearPD" 个对象列表中提取矩阵。


下面简要解释了为什么 as.matrix 在这种情况下有效。注意 nearPD 对象中的矩阵不是矩阵:

is.matrix(A[[1]]$mat)
[1] FALSE

然而,它是一个"Matrix":

class(A[[1]]$mat)
[1] "dpoMatrix"
attr(,"package")
[1] "Matrix"

从帮助文件中的注释,help("as.matrix,Matrix-method")

Loading the Matrix namespace “overloads” as.matrix and as.array in the base namespace by the equivalent of function(x) as(x, "matrix"). Consequently, as.matrix(m) or as.array(m) will properly work when m inherits from the "Matrix" class.

因此,Matrix 包负责 as.matrix 转换 "under the hood."