相关疑难解决方法(0)

Vectorised Rcpp随机二项式绘制

这是这个问题的后续问题:在Rcpp和R中生成相同的随机变量

我正在尝试加速对这种形式的rbinom的向量化调用:

    x <- c(0.1,0.4,0.6,0.7,0.8)
    rbinom(length(x),1 ,x)
Run Code Online (Sandbox Code Playgroud)

在x的实时代码中是一个可变长度的向量(但通常以百万为单位编号).我没有Rcpp的经验,但我想知道我可以使用Rcpp来加快速度.从链接的问题来看,这个Rcpp代码被建议用于@Dirk Eddelbuettel的非矢量化rbinom调用:

    cppFunction("NumericVector cpprbinom(int n, double size, double prob) { \
         return(rbinom(n, size, prob)); }")
    set.seed(42); cpprbinom(10, 1, 0.5)
Run Code Online (Sandbox Code Playgroud)

....并且大约是非Rcpp选项的两倍,但无法处理我的矢量化版本

    cpprbinom(length(x), 1, x)
Run Code Online (Sandbox Code Playgroud)

如何修改Rcpp代码来实现这一点?

谢谢

r rcpp

3
推荐指数
2
解决办法
1218
查看次数

Rcpp本征稀疏矩阵绑定

我正在Rcpp(Eigen)中开发一种算法,该算法要求矩阵使用cbind。我发现R的绑定速度非常快,而使用Eigen的速度非常慢。我想找到一种优化此功能的方法,以便将算法保留在Rcpp中。到目前为止,我已经找到了另一个链接,但是它适用于密集矩阵上的cbind

#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]

using namespace Rcpp;
using namespace Eigen;

// [[Rcpp::export]]
Eigen::SparseMatrix<double> RcppMatrixCbind(Eigen::MappedSparseMatrix<double>& matrix1,
                                            Eigen::MappedSparseMatrix<double>& matrix2) {

  SparseMatrix<double> out(matrix1.rows(), matrix1.cols() + matrix2.cols());
  std::vector<Triplet<double> > tripletList;
  tripletList.reserve(matrix1.nonZeros() + matrix2.nonZeros());
  for (int k = 0; k < matrix1.outerSize(); ++k)
  {
    for (MappedSparseMatrix<double>::InnerIterator it(matrix1, k); it; ++it)
    {
      tripletList.push_back(Triplet<double>(it.row(), it.col(), it.value()));
    }
  }
  for (int k = 0; k < matrix2.outerSize(); ++k)
  {
    for (MappedSparseMatrix<double>::InnerIterator it(matrix2, k); it; ++it)
    {
      tripletList.push_back(Triplet<double>(it.row(), it.col() + matrix1.cols(), it.value()));
    }
  }
  out.setFromTriplets(tripletList.begin(), tripletList.end()); …
Run Code Online (Sandbox Code Playgroud)

r matrix rcpp eigen

1
推荐指数
1
解决办法
256
查看次数

标签 统计

r ×2

rcpp ×2

eigen ×1

matrix ×1