在 Rcpp 中获取全局选项

Get global option in Rcpp

我想在 Rcpp 中获取一个选项的值(例如 "width")。我试过了:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int test_option() {

  Environment base("package:base");
  Function get_option = base["getOption"];
  return get_option("width");
}

// [[Rcpp::export]]
int test_option2() {

  Environment base("package:base");
  Function get_option = base["options"];
  List l_width = get_option("width");
  return l_width[1];
}

第一个函数无法编译,第二个函数使会话崩溃。

知道怎么做吗?

为什么代码不起作用是因为过于依赖 Rcpp 到 R 的自动转换。您将需要创建一个中间步骤。 回想一下 R 没有标量int 数据类型的概念。

让我们看看使用 Rinternal 宏 return编辑的类型 Rf_type2char(TYPEOF(x))

c.f.

#include<Rcpp.h>

// [[Rcpp::export]]
void test_option() {

  Rcpp::Environment base("package:base");
  Rcpp::Function get_option = base["getOption"];
  Rcpp::Rcout << Rf_type2char(TYPEOF(get_option("width")));
}

这给出:

test_option()
# integer

从那里,添加回 return 类型:

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::IntegerVector  get_width() {

  Rcpp::Environment base("package:base");
  Rcpp::Function get_option = base["getOption"];
  Rcpp::IntegerVector out = get_option("width");

  return out;
}

输出:

get_width()
# [1] 155

test_option

如果你这样写,你的第一个函数就可以工作了:

SEXP test_option() {

或者这个:

IntgerVector test_option() {

test_option2

关于你问题中的第二个函数,你在评论中写道你的 objective 是将 SEXP 转换为 int 所以在这种情况下,如果 sSEXP 持有一个整数然后 as<int>(s)INTEGER(s)[0] 是一个 int。这与 IntegerVector 相反。如果你真的想写你想要一个 IntegerVector 然后用 IntegerVector.

替换下面三个出现的 int

将下面 myOption.cpp 中的代码放在当前目录中,然后按照第一行中的说明进行操作。

// To run: library(Rcpp); sourceCpp("myOption.cpp")

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int myOption(CharacterVector x) {
  Environment base( "package:base" ) ;
  Function getOption = base["getOption"];
  SEXP s = getOption(x);
  int i = as<int>(s);
  return i;
}

/*** R
myOption("width")
*/