R调用C++示例

sourceCpp {Rcpp}:Source C++ Code from a File or String

sourceCpp(file = "", code = NULL, env = globalenv(), embeddedR = TRUE, rebuild = FALSE,
  cacheDir = getOption("rcpp.cache.dir", tempdir()), cleanupCacheDir = FALSE,
  showOutput = verbose, verbose = getOption("verbose"), dryRun = FALSE)

file:给出文件路径名的字符串。

code:带有源代码的字符串。如果提供,代码将从该字符串而不是文件中获取。

env:应该提供R函数和模块的环境。

embeddedR:TRUE表示运行嵌入的R代码块。

示例1:斐波那契数列

sourceCpp(code='
  #include 

  // [[Rcpp::export]]
  int fibonacci(const int x) {
    if (x == 0) return(0);
    if (x == 1) return(1);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
  }'
)
> for(i in 0:10)
+ {
+     print(fibonacci(i))
+ }
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
[1] 21
[1] 34
[1] 55

示例2:正弦查表

#include 
using namespace Rcpp;
//sin_C.cpp
// [[Rcpp::export]]
int sin_C(int x) {
  //正弦查表
  //输入x范围1~256
  int sin_rom[]={128, 131, 134, 137, 140, 143, 146, 149, 
                 152, 156, 159, 162, 165, 168, 171, 174, 
                 176, 179, 182, 185, 188, 191, 193, 196, 
                 199, 201, 204, 206, 209, 211, 213, 216, 
                 218, 220, 222, 224, 226, 228, 230, 232, 
                 234, 236, 237, 239, 240, 242, 243, 245, 
                 246, 247, 248, 249, 250, 251, 252, 252, 
                 253, 254, 254, 255, 255, 255, 255, 255};
  int y;
  if(x<=64)
    y=sin_rom[x-1];
  else if(x<=128)
    y=sin_rom[128-x];
  else if(x<=192)
    y=255-sin_rom[x-129];
  else
    y=255-sin_rom[256-x];
  return y;
}

/*** R
x<-y<-1:256
for(i in 1:256)
{
  y[i]<-sin_C(x[i])
}
plot(x,y,type="l")
*/
Rcpp::sourceCpp('sin_C.cpp')

R调用C++示例_第1张图片

你可能感兴趣的:(R调用C++示例)