rcpp - 从给定包中调用函数使用 RcppArmadillo(Rcpp)
问题描述
我正在学习使用 RcppArmadillo(Rcpp) 使代码运行得更快。在实践中,我通常会遇到我想从给定的包中调用一些函数。下面是一个小例子。我想计算套索(或 scad、mcp)的阈值。在 R 中,我们可以使用thresh_est
函数 in library(HSDiC)
,其内容为
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)
然后我尝试通过 RcppArmadillo(Rcpp) 实现上述功能。根据 teuder以及 coatless 和coatless的答案,我编写了下面的代码(保存为thresh_arma.cpp):
#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;
}
然后我编译为
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)
但是,编译失败,我不知道原因。
解决方案
推荐阅读
- angular - .net core3.1 + IdentityServer4 - 每个用户一个会话
- android - 有没有更好的方法来对齐 Android 中不同按钮中的文本?
- c - 在某个重复字符后从字符串中删除文本
- python - 如何使用 Matplotlib 为所有子图设置相同的 y 轴比例?
- oracle - Oracle Apex 交互式网格 - 列类型:开关
- python - 在 Python3 中使用 line.replace 对数字序列重新编号
- google-app-engine - Google App Engine - 改为强制 Content-Length
- tensorflow - 使用循环在 tensorflow 中创建自定义损失函数
- javascript - 关于解构和处理 undefined 的问题
- python - ModuleNotFoundError:没有名为“dask_xgboost”的模块