[Rcpp-devel] Connection between arma and rcpp

Honglang Wang wanghonglang2008 at gmail.com
Tue Jan 29 19:29:52 CET 2013


Dear All,
I have a problem, maybe that's trivial to you, but it's really bothering
me. How to transfer rama objects and rcpp objects easily? A simple test
code is the following:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::export]]
double foo(Function f, NumericVector x) {
  double r = 0.0;
  for (int i=0; i<100; i++)
    r += as<double>(f(x));
  return r;
}

// [[Rcpp::export]]
double fpp(Function f, NumericMatrix Ar) {
  int n = Ar.nrow(), m = Ar.ncol();
  arma::mat A(Ar.begin(),n,m,false);
  A.reshape(m,n);
  arma::mat U(m,1);
  for(int a=0; a<m; a++){
  U(a,1)=foo(f,A.row(a));
  }
  double r = arma::accu(U);
  return r;
}

A <- matrix(rnorm(8),nrow=4)
fpp(mean,A)

In fact, I would like to use apply, a function in R, to replace the for
loop in function fpp. But it does not work in the following code:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::export]]
List foo(Function f, NumericVector x) {
  double r = 0.0;
  for (int i=0; i<100; i++)
    r += as<double>(f(x));
  return List::create(Named("r") = r);

}

// [[Rcpp::export]]
double fpp(Function f1, Function f2, NumericMatrix Ar) {
  int n = Ar.nrow(), m = Ar.ncol();
  arma::mat A(Ar.begin(),n,m,false);
  A.reshape(m,n);
  arma::mat U(m,1)=f2(A,1, function(x) foo(f=f1,x)$r);
  double r = arma::accu(U);
  return r;
}

A <- matrix(rnorm(8),nrow=4)
fpp(mean, apply, A)

Anyone can help me out? Thanks a lot?
Best wishes!

Honglang Wang

Office C402 Wells Hall
Department of Statistics and Probability
Michigan State University
1579 I Spartan Village, East Lansing, MI 48823
wangho16 at msu.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130129/5025b60a/attachment.html>


More information about the Rcpp-devel mailing list