"not a matrix" 当我在 R 中 运行 我的 Rcpp cde 时出错

"not a matrix" error when I run my Rcpp cde in R

我正在尝试在我的 Rcpp 代码中使用 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;   
  }

但是当我想测试它时,例如在 R 中如下所示:

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

我看到这条错误消息:"Error in eBsc(A) : not a matrix"。 我不得不提到 nearPD returns 输出列表,其中第一个是矩阵。

你错了。列表的第一个元素不是矩阵。它是 Matrix 包中定义的 S4 对象。这有效:

#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)
  */

输出:

> 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:如果您需要矩阵,请使用包库中的 as.matrix(在 Rcpp 或 R 中)。

PPS: 显然,在 C++ 代码中不调用 R 函数会更有效。