rcpp 无法在初始化时将 ‘SEXP {aka SEXPREC*}’ 转换为 ‘double’

标签 r rcpp

我正在尝试在 Rcpp 中复制 R 向量化和

我首先尝试以下无故障代码:

#include <Rcpp.h>
using namespace Rcpp;

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

输入call(Time)

> call(Time)
[1] 1919853

然后一个环境版本,也很好用,

#include <Rcpp.h>
using namespace Rcpp;

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

输入call()

> call()
[1] 1919853

现在我正在尝试如下奇怪的事情,

#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;
}

这次我收到一条错误信息:

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

知道出了什么问题吗?

最佳答案

您不能在 Rcpp 的向量之一上调用 R 函数(即 sumc())。这样做:

// [[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;
}

这里的sum()是Rcpp糖函数。

关于rcpp 无法在初始化时将 ‘SEXP {aka SEXPREC*}’ 转换为 ‘double’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596567/

相关文章:

r - 使用自适应窗口长度计算 data.table 中的滚动平均值

从数据框中删除列中包含重复信息的行

regex - R中的模式匹配和替换

c++ - 在 Rcpp 中选择一个不连续的子矩阵

rcpp:如何在函数中设置字符参数?

R CRAN,R3.2升级后安装库Rcpp失败

c++ - 如何在 Rcpp 中构建常量矩阵?

performance - R中数据的快速边界

r - 将列粘贴在一起但忽略 NA

r - 使用 purrr 来捕获 mapply 的错误