adaodante - 3 months ago 27

R Question

I have n matrices of which I am trying to apply

`nearPD()`

`Matrix`

I have done this using the following code:

`A<-lapply(b, nearPD)`

where b is the list of n matrices.

I now would like to convert the list A into matrices. For an individual matrix I would use the following code:

`A<-matrix(runif(n*n),ncol = n)`

PD_mat_A<-nearPD(A)

B<-as.matrix(PD_mat_A$mat)

But I am trying to do this with a list. I have tried the following code but it doesn't seem to work:

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

Any help would be appreciated. Thank you.

Here is a code so you can try and reproduce this:

`n<-10`

generate<-function (n){

matrix(runif(10*10),ncol = 10)

}

b<-lapply(1:n, generate)

Answer

Here is the simplest method using `as.matrix`

as noted by @nicola in the comments below and (a version using `apply`

) by @cimentadaj in the comments above:

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

My original answer, exploiting the nearPD data structure was

With a little fiddling with the `nearPD`

object type, here is an extraction method:

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

Below is some commentary on how I arrived at my answer.

This object is fairly complicated as `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"

You are interested in the "mat" which is accessed by `$mat`

. The `@`

symbols show that "mat" is an `s4`

object and its components are accessed using `@`

. The components of interest are "x", the matrix content, and "Dim" the dimension of the matrix. The code above puts this information together to extract the matrices from the list of "nearPD" objects.

Below is a brief explanation of why `as.matrix`

works in this case. Note the matrix inside a nearPD object is not a matrix:

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

However, it is a "Matrix":

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

From the note in the help file, `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.

So, the `Matrix`

package is taking care of the `as.matrix`

conversion "under the hood."

Source (Stackoverflow)

Comments