我正在尝试在Rcpp中创建某种类型的sapply函数,其工作方式如下:-函数采用任何类型x
和任何cpp函数的两个参数向量(可能的有趣输出-bool,int,double,string)。-我想将fun
应用于x
的选定元素。-输出向量可以是取决于fun
输出的任何类型(可以与x
不同)。在apply中,将存在一个循环,用于将fun
中的单个值分配给res
输出。
我正在尝试通过实现此目标,但是每次输出变为Rcpp::List
而不是Rcpp::Vector<double>
。
这里是代码,为了简化示例,我没有写apply_cpp_fun
的全文。如您所见,即使我通过<double>function
,模板也会将Vector描述为double (*)(Rcpp::Vector<14, Rcpp::PreserveStorage>)
。
#include <Rcpp.h>
double cpp_sum(Rcpp::NumericVector x) {
int n = x.size();
double cursum = 0;
for (int i = 0; i < n; i++) {
cursum += x(i);
}
return cursum;
}
template <int ITYPE, typename ftype>
Rcpp::Vector<Rcpp::traits::r_sexptype_traits<ftype>::rtype>
apply_cpp_fun(Rcpp::Vector<ITYPE>& x,
ftype fun) {
int n = x.size();
double xx = 5.0;
Rcpp::Rcout << "type of xx: " << demangle(typeid(xx).name()).c_str() << std::endl;
Rcpp::Rcout << "function type: " << demangle(typeid(ftype).name()).c_str() << std::endl;
const int OTYPE = Rcpp::traits::r_sexptype_traits<ftype>::rtype;
Rcpp::Rcout << "SEXP type: " << OTYPE << std::endl;
Rcpp::Vector<OTYPE> res(n);
return res;
}
// [[Rcpp::export]]
SEXP cumsum_cpp(Rcpp::NumericVector x) {
return apply_cpp_fun(x, cpp_sum);
}
调用函数以查看结果
cumsum_cpp(as.numeric(1:2))
# type of xx: double
# function type: double (*)(Rcpp::Vector<14, Rcpp::PreserveStorage>)
# SEXP type: 19
# [[1]]
# NULL
#
# [[2]]
# NULL
如何解决此问题以使应用程序在输入类型和输出方面保持灵活?感谢您的任何建议。
在我看来,您没有利用Rcpp在“幕后”在c ++类型和R类型之间进行转换的能力,从而使自己变得更难。我倾向于编写“纯C ++”,然后仅使用Rcpp神奇地导出到R,而无需尝试打开其内部。