I am learning to use RcppArmadillo(Rcpp) to make the code run faster.
In practice, I usually encounter that I want to call some functions from given packages.
The below is a little example.
I want to calculate the thresholds of lasso (or scad, mcp). In R we can use
the thresh_est
function in library(HSDiC)
, which reads
library(HSDiC) # acquire the thresh_est() function
# usage: thresh_est(z, lambda, tau, a = 3, penalty = c("MCP", "SCAD", "lasso"))
# help: ?thresh_est
z = seq(-5,5,length=500)
thresh = thresh_est(z,lambda=1,tau=1,penalty="lasso")
# thresh = thresh_est(z,lambda=1,tau=1,a=3,penalty="MCP")
# thresh = thresh_est(z,lambda=1,tau=1,a=3.7,penalty="SCAD")
plot(z,thresh)
Then I try to realize the above via RcppArmadillo(Rcpp). According to the answers of teuder as well as coatless and coatless, I write the code (which is saved as thresh_arma.cpp) below:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp; //with this, Rcpp::Function can be Function for short, etc.
using namespace arma; // with this, arma::vec can be vec for short, etc.
// using namespace std; //std::string
// [[Rcpp::export]]
vec thresh_arma(vec z, double lambda, double a=3, double tau=1, std::string penalty) {
// Obtaining namespace of the package
Environment pkg = namespace_env("HSDiC");
// Environment HSDiC("package:HSDiC");
// Picking up the function from the package
Function f = pkg["thresh_est"];
// Function f = HSDiC["thresh_est"];
vec thresh;
// In R: thresh_est(z, lambda, tau, a = 3, penalty = c("MCP", "SCAD", "lasso"))
if (penalty == "lasso") {
thresh = f(_["z"]=z,_["lambda"]=lambda,_["a"]=a,_["tau"]=tau,_["penalty"]="lasso");
} else if (penalty == "scad") {
thresh = f(_["z"]=z,_["lambda"]=lambda,_["a"]=a,_["tau"]=tau,_["penalty"]="SCAD");
} else if (penalty == "mcp") {
thresh = f(_["z"]=z,_["lambda"]=lambda,_["a"]=a,_["tau"]=tau,_["penalty"]="MCP");
}
return thresh;
}
Then I do the compilation as
library(Rcpp)
library(RcppArmadillo)
sourceCpp("thresh_arma.cpp")
# z = seq(-5,5,length=500)
# thresh = thresh_arma(z,lambda=1,tau=1,penalty="lasso")
# # thresh = thresh_arma(z,lambda=1,a=3,tau=1,penalty="mcp")
# # thresh = thresh_arma(z,lambda=1,a=3.7,tau=1,penalty="scad")
# plot(z,thresh)
However, the compilation fails and I have no idea about the reasons.