本文介绍了使用Rcpp将循环从R转换为C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Rcpp提高我的一些R代码的速度。但是,我对C ++的了解非常少。所以,我检查了Rcpp提供的文档和Dirk Eddelbuttel的网站提供的其他文档。阅读所有的东西后,我试图执行一个简单的循环,我写在R.不幸的是,我无法做到。这里是R函数:

I want to improve the speed of some of my R code using Rcpp. However, my knowledge of C++ is very little. So, I checked the documentation provided with Rcpp, and other documents provided at Dirk Eddelbuttel’s site. After reading all the stuff, I tried to execute a simple loop that I wrote in R. unfortunately, I was unable to do it. Here is the R function:

Inverse Wishart

beta = matrix(rnorm(15),ncol=3)

a = rnorm(3)

InW = function(beta,a) {

    n = nrow(beta)
    p = ncol(beta)
    I = diag(rep(1,times = p))
    H = matrix(0,nrow=p,ncol=p)
    for(i in 1:n){
    subBi = beta[i,]
          H = H + tcrossprod(a - subBi)
        }
    H = H + p * I

    T = t(chol(chol2inv(chol(H))))
    S = 0
    for(i in 1:(n+p)){
        u <- rnorm(p)
        S = S + tcrossprod(T %*% u)
        }
    D = chol2inv(chol((S)))
    ans = list(Dinv = S,D=D)
}



我真的很感激,如果有人可以帮助我,因为它会作为学习Rcpp的起点。

I truly, appreciate if someone can help me as it will serve as starting point in learning Rcpp.

推荐答案

RcppArmadillo的一个基本示例就是这样,

A basic example of RcppArmadillo goes like this,

require(RcppArmadillo)
require(inline)

code <- '
  arma::mat beta = Rcpp::as<arma::mat>(beta_);
  int n = beta.n_rows; int p = beta.n_cols;
  arma::mat Ip = arma::eye<arma::mat>( p, p );
  int ii;
  double S=0;
  for (ii=0; ii<(n+p); ii++) {
    S += ii; // dummy calculation
  }
  return Rcpp::wrap(S);
 '

fun <- cxxfunction(signature(beta_ ="matrix"),
                       code, plugin="RcppArmadillo")

m <- matrix(1:9,3)
fun(m)

以找到更高级的位元。

and you can browse armadillo's doc to find the more advanced bits and pieces.

这篇关于使用Rcpp将循环从R转换为C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:45