当我在R中运行我的Rcpp cde时,"不是矩阵"错误

Ham*_*m82 1 r matrix armadillo rcpp

我试图nearPD在我的Rcpp代码中使用函数.虽然看起来微不足道,但我找不到为什么它不起作用.它是我的代码的简化版本:

#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;   
  }
Run Code Online (Sandbox Code Playgroud)

但是当我想测试它时,例如如下R:

A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0
d<-eBsc(A)
Run Code Online (Sandbox Code Playgroud)

我看到这个错误信息:"Error in eBsc(A) : not a matrix".我必须提到nearPD返回一个输出列表,第一个是矩阵.

Rol*_*and 6

你误会了.列表的第一个元素不是矩阵.它是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)
  */
Run Code Online (Sandbox Code Playgroud)

输出:

> 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
Run Code Online (Sandbox Code Playgroud)

PS:如果你需要as.matrix从包基(在Rcpp或R中)使用矩阵.

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