我正在使用Rcpp加速一些R代码。但是,我确实在为类型而苦苦挣扎-因为这些类型在R中是陌生的。这是我想要做的事情的简化版本:
#include <RcppArmadillo.h>
#include <algorithm>
//[[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
NumericVector fun(SEXP Pk, int k, int i, const vec& a, const mat& D) {
// this is dummy version of my actual function - with actual arguments.;
// I'm guessing SEXP is going to need to be replaced with something else when it's called from C++ not R.;
return D.col(i);
}
// [[Rcpp::export]]
NumericVector f(const arma::vec& assignment, char k, int B, const mat& D) {
uvec k_ind = find(assignment == k);
NumericVector output(assignment.size()); // for dummy output.
uvec::iterator k_itr = k_ind.begin();
for(; k_itr != k_ind.end(); ++k_itr) {
// this is R code, as I don't know the best way to do this in C++;
k_rep = sample(c(assignment[assignment != k], -1), size = B, replace = TRUE);
output = fun(k_rep, k, *k_itr, assignment, D);
// do something with output;
}
// compile result, ultimately return a List (after I figure out how to do that. For right now, I'll cheat and return the last output);
return output;
}
我遇到的问题是assignment
的随机抽样。我知道sample
已在Rarmadillo
中实现。但是,我可以看到两种解决方法,但我不确定哪种方法更有效/可行。
assignment
值表。将assignment == k
替换为-1,并将其“计数”设置为1。assignment
向量的相关子集复制到一个新的向量中,该向量具有一个额外的-1点。我想说的是,方法1会更有效,除了assignment
当前为arma::vec
类型,而且我不确定如何用该表制作表–或将其转换为更兼容的格式需要付出一定的代价。我想我可以实现方法2,但我希望避免使用昂贵的副本。
感谢您提供的任何见解。
答案 0 :(得分:-1)
许多变量声明与您所做的赋值不一致,例如,assignment = k无法比较,因为赋值具有实际值,并且k是一个字符。由于问题写得不好,我随时可以更改变量类型。这个编译..
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::export]]
arma::vec fun(const Rcpp::NumericVector& Pk, int k, unsigned int i, const arma::ivec& a, const arma::mat& D)
{
return D.col(i);
}
// [[Rcpp::export]]
Rcpp::NumericMatrix f(const arma::ivec& assignment, int k, unsigned int B, const arma::mat& D)
{
arma::uvec k_ind = find(assignment == k);
arma::ivec KK = assignment(find(assignment != k));
//these 2 row are for KK = c(assignment[assignment != k], -1)
//I dont know what is this -1 is for, why -1 ? maybe you dont need it.
KK.insert_rows(KK.n_rows, 1);
KK(KK.n_rows - 1) = -1;
arma::uvec k_ind_not = find(assignment != k);
Rcpp::NumericVector k_rep(B);
arma::mat output(D.n_rows,k_ind.n_rows); // for dummy output.
for(unsigned int i =0; i < k_ind.n_rows ; i++)
{
k_rep = Rcpp::RcppArmadillo::sample(KK, B, true);
output(arma::span::all, i) = fun(k_rep, k, i, assignment, D);
// do something with output;
}
// compile result, ultimately return a List (after I figure out how to do that. For right now, I'll cheat and return the last output);
return Rcpp::wrap(output);
}
这不是最优化的(因为这个问题是虚假的),这写得不好,因为我认为R在搜索向量的索引方面会足够快(因此在R中执行此操作,而在Rcpp中仅实现乐趣)。 。在这里浪费时间不是有用的,还有其他问题需要在Rcpp中实现求解器,而不是在搜索这些东西... 但这不是一个有用的问题,因为您要求的是算法而不是功能签名