Rcpp cannot convert ‘SEXP {aka SEXPREC*}’ to ‘double’ in initialization

浪子不回头ぞ 提交于 2019-12-13 01:54:17

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/36596567/rcpp-cannot-convert-sexp-aka-sexprec-to-double-in-initialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!