Ham82 -4 years ago 45

R Question

I am trying to use

`nearPD`

`#include <RcppArmadillo.h>`

// [[Rcpp::depends(RcppArmadillo)]]

using namespace arma;

using namespace Rcpp;

// [[Rcpp::export]]

mat eBsc(mat R){

Rcpp::Environment Matrix("package:Matrix");

Rcpp::Function nearPD = Matrix["nearPD"];

Rcpp::List PD=nearPD(R);

mat P = PD["mat"];

return P;

}

But when I want to test it ,e.g. as below in R:

`A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0`

d<-eBsc(A)

I see this error message:

`"Error in eBsc(A) : not a matrix"`

I have to mention that the nearPD returns a list of outputs which the first one is a matrix.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You are mistaken. The first element of the list is not a matrix. It is an S4 object defined in package Matrix. This works:

```
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
S4 eBsc(NumericMatrix R){
Rcpp::Environment Matrix("package:Matrix");
Rcpp::Function nearPD = Matrix["nearPD"];
Rcpp::List PD=nearPD(R);
S4 P = PD["mat"];
return P;
}
/*** R
library(Matrix)
A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0
eBsc(A)
*/
```

Output:

```
> library(Matrix)
> A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0
> eBsc(A)
3 x 3 Matrix of class "dpoMatrix"
[,1] [,2] [,3]
[1,] 1.1035534 0.8535534 0.1035534
[2,] 0.8535534 1.2071068 0.8535534
[3,] 0.1035534 0.8535534 1.1035534
```

PS: If you need a matrix use `as.matrix`

from package base (in Rcpp or in R).

PPS: Obviously, it would be more efficient not to call an R function in C++ code.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added