gpt4 book ai didi

r - 在 R 中运行 Rcpp cde 时出现 "not a matrix"错误

转载 作者:行者123 更新时间:2023-12-02 07:21:38 24 4
gpt4 key购买 nike

我正在尝试在我的 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)

我看到此错误消息:“eBsc(A) 中的错误:不是矩阵”。我不得不提到 nearPD 返回一个输出列表,其中第一个是矩阵。

最佳答案

你错了。列表的第一个元素不是矩阵。它是 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:如果您需要矩阵,请使用 package base 中的 as.matrix(在 Rcpp 或 R 中)。

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

关于r - 在 R 中运行 Rcpp cde 时出现 "not a matrix"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44496450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com