[Rcpp-devel] Connection between arma and rcpp

Kevin Ushey kevinushey at gmail.com
Tue Jan 29 19:59:09 CET 2013


In this case, I have to ask, 'why'? You want to use C++ to call R functions
on R functions? This isn't going to give you any speed benefit, and it's
not going to be any better than a base-R solution... if you want an 'apply'
framework for matrices, you should roll your own, or consider using
each_row or each_col for the arma matrices if your function is simple
enough.

-Kevin

On Tue, Jan 29, 2013 at 10:29 AM, Honglang Wang
<wanghonglang2008 at gmail.com>wrote:

> 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
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130129/e1d48a55/attachment.html>


More information about the Rcpp-devel mailing list