Rcpp 评估错误:下标越界

3

我想在Rcpp代码中使用“glasso”包,cpp代码如下:

#include <RcppArmadillo.h>
 // [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
List sec(arma::mat x,double lam){
Environment gla("package:glasso");
Function gl=gla["glasso"];
double thr=1e-2;bool approx=0;
bool diag=1; bool nu=0;
List bc(5);
bc=gl(x,lam,nu,thr,thr,approx,approx,nu,nu,diag);
return(bc);}

但是当我在 R 中引用代码时,出现了以下错误。
set.seed(100)
x<-matrix(rnorm(50*10),ncol=10)
s<- var(x)
library(glasso)
a<-sec(s, 0.01)
"Error in sec(s, 0.01) : Evaluation error: subscript out of bounds."

我查看了“glasso”包的文档,结果列表包含5个值,所以我很困惑问题在哪里。


我假设你明白从C++调用R代码仍然以R的速度运行。 - Dirk Eddelbuettel
1个回答

4
你的代码中有几个问题。最新版本的glasso()函数返回一个由7个(而不是5个)元素组成的列表。在我的答案中,我将使用这个版本的glasso()函数。在Rcpp调用中向glasso()函数传递NULL值时,请使用R_NilValue。在我的示例中,我省略了一些参数列表末尾的值,因为我不确定你想要传递哪些值(看起来你正在使用这个包的旧版本)。
#include <RcppArmadillo.h>
 // [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
List sec(arma::mat x,double lam){
Environment gla("package:glasso");
Function gl=gla["glasso"];
double thr=1e-2;bool approx=0;
bool diag=1; bool nu=0;
List bc(7);
bc = gl(x, lam, R_NilValue,thr,thr,approx,diag);
return(bc);}

这是我的R代码:
library(Rcpp)

sourceCpp("test.cpp")

library(glasso)
set.seed(100)
x<-matrix(rnorm(50*10),ncol=10)
s<- var(x)
a<-sec(s, 0.01)


   #output
   a
    # $w
    # [,1]        [,2]         [,3]         [,4]        [,5]        [,6]
    # [1,]  0.680779447  0.33966152 -0.009663187 -0.108946142  0.07360211  0.21757108
    # [2,]  0.339661517  1.43157518 -0.042659411 -0.190859910  0.11234565  0.15097851
    #...
    # 
    # $wi
    # [,1]        [,2]        [,3]         [,4]         [,5]        [,6]
    # [1,]  2.26552621 -0.57002634  0.00000000  0.114629054 -0.159489421 -0.46727499
    # [2,] -0.58556329  1.01623488 -0.04678184  0.236972034  0.000000000 -0.03616841
    #...
    # 
    # $loglik
    # [1] -43.31512
    # 
    # $errflag
    # [1] 0
    # 
    # $approx
    # [1] FALSE
    # 
    # $del
    # [1] 0.008940439
    # 
    # $niter
    # [1] 1

谢谢您的回答,我认为它对我的问题有用。对于这个问题,我还有两个问题。首先,在某些R函数中,当参数具有默认值时,如果我不想更改该值,那么在这种情况下,是否仍然需要设置参数值?其次,在我的示例中,如果我想将参数start="warm"设置为什么类型?是“char”还是“int”? - Xia.Song
@Xiaol.Song 如果默认值在最后 - 是的,您不必定义它们。至于开始,以下内容有效:char start [] =“cold”; bc = gl(x,lam,R_NilValue,thr,thr,approx,diag,start,R_NilValue); - Katia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接