3

I am trying to duplicate the R vectorised sum in Rcpp

I first try the following trouble-free code:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double call(NumericVector x){
  return sum(x);
}

Type call(Time)

> call(Time)
[1] 1919853

Then an environment version, also works well,

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double call(){
  Environment env = Environment::global_env();
  NumericVector Time = env["Time"];
  return sum(Time);
}

Type call()

> call()
[1] 1919853

Now I am trying something weird as following,

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double call(){
  Environment base("package:base");
  Function sumc = base["sum"];
  Environment env = Environment::global_env();
  NumericVector Time = env["Time"];
  double res = sumc(Time);
  return res;
}

This time I got a error message:

trycpp.cpp:10:25: error: cannot convert ‘SEXP {aka SEXPREC*}’ to ‘double’ in initialization
double res = sumc(Time);

Any idea what's going wrong ?

skyindeer
  • 165
  • 2
  • 11

1 Answers1

6

You cannot call an R function (ie sumc() on one of Rcpp's vectors. Do this:

// [[Rcpp::export]]
double mycall(){
  Environment base("package:base");
  Function sumc = base["sum"];
  Environment env = Environment::global_env();
  NumericVector Time = env["Time"];
  double res = sum(Time);
  return res;
}

Here sum() is the Rcpp sugar function.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Thanks @Dirk Eddelbuettel, the reason I try the last method is I want to duplicate the following R vectorised summation sum(Time[Time<100]). Any hints on how to do it in Rcpp ? – skyindeer Apr 13 '16 at 11:46
  • Yes, several posts here (including _yesterday_ !!) on how to do indexing. Thanks for accepting the answer, you can also upvote (click on up-arrow). – Dirk Eddelbuettel Apr 13 '16 at 12:03