提高 R 脚本性能的最简单、最快捷的方法是更改脚本的问题部分并用 C++ 重写它们。Rcpp包提供了 R 和 C++ 之间的接口。
1. cppFunction()转换简单的C++函数
### 1. cppFunction()转换简单的C++函数
library(Rcpp)
cppFunction(code='int fibonacci(const int x){if(x < 2) return x;if(x > 40) return -1; // 太大的x值会占用过多计算资源return ( fibonacci(x-1) + fibonacci(x-2) );}
')
print(fibonacci(10))
2. sourceCpp()转换C++程序
sourceCpp(code='
#include <Rcpp.h>
using namespace Rcpp;//[[Rcpp::export]]NumericVector iters(NumericVector x){int n = x.size();NumericVector y(n);y[0] = x[0];double sign=-1;for(int t=1; t<n; t++){sign *= -1;y[t] = sign*y[t-1] + x[t];}return y;}
')print(iters(1:5))
3. 用sourceCpp()转换C++源文件中的程序
# test.cpp文件
#// [[Rcpp::export]]
#int multiplicationcpp(int a, int b) {
# int sum = a * b ;
# return sum;
#}sourceCpp("path/to/your/file/test.cpp")
multiplicationcpp(a = 10 , b = 5)
4. Rcpp项目
RStudio中新建 Rcpp项目 (Create R Package Using Rcpp)(需要下载更新C++编译器)
编写R文件,Rcpp文件
进入testRcpp文件夹 setwd("/Users/zhengxueming/Projects/testRcpp")
运行 Rcpp::compileAttributes()
更新 RcppExports.R 和RcppExports.cpp文件
注:通过命令创建项目骨架
setwd("/Users/zhengxueming/Projects")
library(Rcpp)
Rcpp.package.skeleton("testRcpp")
运行 Rcpp::compileAttributes()后,不会更新RcppExports.R 和RcppExports.cpp文件。
参考:
https://zhuanlan.zhihu.com/p/442412744
https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/rcpp.html
https://www.jb51.net/article/227491.htm