Rcpp 使用参数列表调用 R 函数

问题描述 投票:0回答:1

我想通过传递参数列表来从使用 Rcpp 和 R 函数定义的 C++ 函数进行调用,其方式类似于在 R 中使用 do.call。 这是一个愚蠢的例子:

假设我有一个向量并且我想计算截尾平均值。两种可能的方法是

x = rnorm(100)
mean(x, trim = 0.1)
do.call("mean", list(x = x, trim = 0.1))

在我的具体情况下,使用 do.call 更好,因为它可能是要调用的函数使用的几个参数的列表。

根据 stackoverflow 中找到的一些示例,我尝试用 C++ 实现上述内容,如下所示:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double foo(Function f, List args)
{
    double out = as<double>(f(args));
    return out;
}

如果 args 是一个列表,上面的代码不起作用,但只有当 args 是一个值向量时才起作用。

如有任何帮助,我们将不胜感激。

LS

r rcpp
1个回答
1
投票

我不太确定以下是否是您所期望的。

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
double foo (Function f, NumericVector x) {
  double out = Rcpp::as<double>(f(x, Named("trim", 0.1)));
  return out;
}

/*
> x = rnorm(100)
> do.call("mean", list(x = x, trim = 0.1))
[1] 0.1832635
> Rcpp::sourceCpp("test.cpp")
> foo(mean, x)
[1] 0.1832635
*/
© www.soinside.com 2019 - 2024. All rights reserved.