Dear All,<br>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:<br>// [[Rcpp::depends(RcppArmadillo)]]<br>
#include <RcppArmadillo.h><br>using namespace Rcpp;<br>// [[Rcpp::export]]<br>double foo(Function f, NumericVector x) {<br>  double r = 0.0;<br>  for (int i=0; i<100; i++)<br>    r += as<double>(f(x));<br>  return r;<br>
}<br><br>// [[Rcpp::export]]<br>double fpp(Function f, NumericMatrix Ar) {<br>  int n = Ar.nrow(), m = Ar.ncol();<br>  arma::mat A(Ar.begin(),n,m,false);<br>  A.reshape(m,n);<br>  arma::mat U(m,1);<br>  for(int a=0; a<m; a++){<br>
  U(a,1)=foo(f,A.row(a));<br>  }<br>  double r = arma::accu(U);<br>  return r;<br>}<br><br>A <- matrix(rnorm(8),nrow=4)<br>fpp(mean,A)<br><br>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:<br>
// [[Rcpp::depends(RcppArmadillo)]]<br>#include <RcppArmadillo.h><br>using namespace Rcpp;<br>// [[Rcpp::export]]<br>List foo(Function f, NumericVector x) {<br>  double r = 0.0;<br>  for (int i=0; i<100; i++)<br>
    r += as<double>(f(x));<br>  return List::create(Named("r") = r);<br><br>}<br><br>// [[Rcpp::export]]<br>double fpp(Function f1, Function f2, NumericMatrix Ar) {<br>  int n = Ar.nrow(), m = Ar.ncol();<br>
  arma::mat A(Ar.begin(),n,m,false);<br>  A.reshape(m,n);<br>  arma::mat U(m,1)=f2(A,1, function(x) foo(f=f1,x)$r);<br>  double r = arma::accu(U);<br>  return r;<br>}<br><br>A <- matrix(rnorm(8),nrow=4)<br>fpp(mean, apply, A)<br>
<br>Anyone can help me out? Thanks a lot?<br clear="all"><div><div>Best wishes!</div><div> </div><div>Honglang Wang</div><div> </div><div>Office C402 Wells Hall</div><div>Department of Statistics and Probability</div><div>
Michigan State University</div><div>1579 I Spartan Village, East Lansing, MI 48823</div><div><a href="mailto:wangho16@msu.edu" target="_blank">wangho16@msu.edu</a></div></div>