gpt4 book ai didi

c++ - 将 R 函数作为参数传递给 RCpp 函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:31 27 4
gpt4 key购买 nike

我正在尝试运行类似

的东西

R

my_r_function <- function(input_a) {return(input_a**3)}
RunFunction(c(1,2,3), my_r_function)

CPP

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector RunFunction(NumericVector a, Function func)
{
NumericVector b = NumericVector(a.size());
for(int i=0; i<a.size(); i++)
b[i] = func(a[i]);
return b;
}

我如何让“Function func”在 Rcpp 中实际工作?

附言我知道有很多方法可以在没有 Rcpp 的情况下执行此操作(此示例想到了 apply ),但我只是以此为例来演示我在寻找什么。

最佳答案

您应该能够使用我上面提供的链接中的示例来使您的代码正常工作;但你也应该注意德克的警告,

Calling a function is simple and tempting. It is also slow as there are overheads involved. And calling it repeatedly from inside your C++ code, possibly buried within several loops, is outright silly.

这可以通过稍微修改上面的代码并对两个版本进行基准测试来证明:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector RunFunction(Rcpp::NumericVector a, Rcpp::Function func)
{
Rcpp::NumericVector b = func(a);
return b;
}

// [[Rcpp::export]]
Rcpp::NumericVector RunFunction2(Rcpp::NumericVector a, Rcpp::Function func)
{
Rcpp::NumericVector b(a.size());
for(int i = 0; i < a.size(); i++){
b[i] = Rcpp::as<double>(func(a[i]));
}
return b;
}

/*** R
my_r_function <- function(input_a) {return(input_a**3)}
x <- 1:10
##
RunFunction(x,my_r_function)

RunFunction2(x,my_r_function)
##
library(microbenchmark)
microbenchmark(
RunFunction(rep(1:10,10),my_r_function),
RunFunction2(rep(1:10,10),my_r_function))

Unit: microseconds
expr min lq mean median uq max neval
RunFunction(rep(1:10, 10), my_r_function) 21.390 22.9985 25.74988 24.0840 26.464 43.722 100
RunFunction2(rep(1:10, 10), my_r_function) 843.864 903.0025 1048.13175 951.2405 1057.899 2387.550 100

*/

注意 RunFunctionRunFunction2 快 40 倍: 在前者中,我们只承担调用 func 的开销从 C++ 代码内部一次,而在后一种情况下,我们必须对输入 vector 的每个元素进行交换。如果您尝试在更长的 vector 上运行它,我相信您会看到 RunFunction2 的性能要差得多相对于 RunFunction .因此,如果您要从 C++ 代码内部调用 R 函数,您应该尝试利用 R 的 native 矢量化(如果可能)而不是在循环中重复调用 R 函数,至少对于相当简单的像 x**3 这样的计算.

此外,如果您想知道为什么您的代码无法编译,那是因为这一行:

b[i] = func(a[i]);

你可能遇到了错误

cannot convert ‘SEXP’ to ‘Rcpp::traits::storage_type<14>::type {aka double}’ in assignment

我通过包装 func(a[i]) 的返回值来解决这个问题在 Rcpp::as<double>()多于。然而,这显然是不值得的,因为无论如何你最终都会得到一个更慢的函数。

关于c++ - 将 R 函数作为参数传递给 RCpp 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391472/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com