Hi all,

I'm attempting to write a simple version of tapply in C++ (see
attached).  However, when I run tapply2(1, 1, sum) (which should
return 1), R segfaults.  If I run R with gdb, I get the following
stack trace:

#0  0x03942120 in tapply2 (x=@0xbfffda68, i=@0xbfffda58,
fun=@0xbfffda50) at tapply.cpp:22
#1  0x0394298a in Rcpp::CppFunction_WithFormals3<Rcpp::Vector<14>,
Rcpp::Vector<14>, Rcpp::Vector<13>, Rcpp::Function>::operator()
(this=0x7f71c0, args=0xbfffdabc) at Module_generated_CppFunction.h:311
#2  0x0385b8b1 in InternalFunction_invoke ()
...

where line 22 is return out;

I suspect it's something to do with the my coercion between
std::vector and NumericVector to call the function, or between the
SEXP output and NumericVector to store the output:

  std::vector< std::vector<double> >::iterator g_it = groups.begin();
  NumericVector::iterator o_it = out.begin();
  for(; g_it != groups.end(); ++g_it, ++o_it) {
    *o_it = as<double>(fun(wrap(*g_it)));
  }

I'd appreciate any hints as to how to solve this particular problem,
as well as any general debugging strategies.

Thanks!

Hadley

-- 
RStudio / Rice University
http://had.co.nz/
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector tapply2(NumericVector x, IntegerVector i, Function fun) {
  std::vector< std::vector<double> > groups;
  
  NumericVector::iterator x_it;
  IntegerVector::iterator i_it;
  
  for(x_it = x.begin(), i_it = i.begin(); x_it != x.end(); ++x_it, ++i_it) {
    groups[*i_it].push_back(*x_it);
  }
  
  NumericVector out(groups.size());
  
  std::vector< std::vector<double> >::iterator g_it = groups.begin();
  NumericVector::iterator o_it = out.begin();
  for(; g_it != groups.end(); ++g_it, ++o_it) {
    *o_it = as<double>(fun(wrap(*g_it)));
  }
  return out;
}
_______________________________________________
Rcpp-devel mailing list
[email protected]
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to