I want to use the "glasso" package in Rcpp code, and the cpp code is as follow:
#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);}
But When I source the code in R and I get follow error.
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."
I check document of "glasso" package, the result list contain 5 values, so I'm confused where is the problem.
There are a couple problems in your code. The latest version of glasso() function returns a list of 7 (not 5) In my answer I will use this version of glasso(). To pass NULL value to glasso() function within Rcpp call, use R_NilValue. In my example I omitted a few values at the end of argument list glasso() function since I was not sure what values you want to pass there (it looks like you are using an older version of this package):
#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);}
Here is my R code:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With