Rcppクラスとベクトル

Rcpp で R コードを最適化する

Romain François

Consulting Datactive, ThinkR

これまでの復習

  • C++関数の作成 ✅
  • ループの記述 ✅
Rcpp で R コードを最適化する

ベクトルクラス

Rcppのベクトルクラス:

  • NumericVectornumericベクトル(例:c(1,2,3)
  • IntegerVectorinteger(例:1:3
  • LogicalVectorlogical(例:c(TRUE, FALSE)
  • CharacterVector:文字列(例:c("a", "b", "c")

その他:

  • List:任意のRオブジェクトのリスト
Rcpp で R コードを最適化する

ベクトルクラスのAPI

主なメソッド:

  • x.size():ベクトルxの要素数を返す
  • x[i]:ベクトルxi番目の要素を返す
Rcpp で R コードを最適化する

C++のインデックス

C++のインデックスは0始まりです。インデックスは先頭からのオフセットを表します。

// first element of the vector
x[0]

// last element
x[x.size()-1]

Rのインデックスは1始まりです。

# first 
x[1]

# last
x[length(x)]
Rcpp で R コードを最適化する

Rcpp で R コードを最適化する

ベクトルの最初の要素

// x comes from somewhere else (patience ...)
NumericVector x = ... ; 

double value = x[0] ;

x[0] = 12.0 ;
Rcpp で R コードを最適化する

ベクトルの最後の要素

// x comes from somewhere else (patience ...)
NumericVector x = ... ; 
int n = x.size() ;

double value = x[n-1] ;

x[n-1] = 12.0 ;
Rcpp で R コードを最適化する

ベクトルのループ処理

// x comes from somewhere
NumericVector x = ... ; 
int n = x.size() ;

for( int i=0; i<n; i++){
    // manipulate x[i]
}

Rcpp で R コードを最適化する

練習しましょう!

Rcpp で R コードを最適化する

Preparing Video For Download...