Vektör oluşturma

Rcpp ile R Kodunu Optimize Etme

Romain François

Consulting Datactive, ThinkR

R tarafında bir vektör al

C++ kodu

// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

R'den çağrılır

x <- c(13.2, 34.1)
extract(x, 0)

x[1]
13.2

13.2
Rcpp ile R Kodunu Optimize Etme
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

Birkaç durum

# x zaten sayısal bir vektör
extract( c(13.3, 54.2), 0 )
13.3
# x bir tamsayı vektörü, önce sayısal vektöre dönüştürülür
extract( 1:10, 0 )
1
Rcpp ile R Kodunu Optimize Etme
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}
# dönüştürme mümkün değil: hata
extract( letters, 0 )
Error in extract(letters, 0) : 
  Not compatible with requested type: [type=character; target=double].
Rcpp ile R Kodunu Optimize Etme

Belirli boyutta vektör oluştur

// [[Rcpp::export]]
NumericVector ones(int n){
    // n boyutunda yeni bir sayısal vektör oluştur
    NumericVector x(n) ;    
    // üzerinde işlem yap
    for( int i=0; i<n; i++){
        x[i] = 1 ; }
    return x ;
}

ones'ı R'den çağırma:

ones(10)
1 1 1 1 1 1 1 1 1 1
Rcpp ile R Kodunu Optimize Etme

Yapıcı (constructor) varyantları

double value = 42.0 ;
int n = 20 ;

// 20 boyutunda bir sayısal vektör oluştur 
// tüm değerleri 42 olsun
NumericVector x( n, value ) ;

Rcpp ile R Kodunu Optimize Etme

Verilen değer kümesi

NumericVector x = NumericVector::create( 1, 2, 3 );

CharacterVector s = CharacterVector::create( "pink", "blue" );
Rcpp ile R Kodunu Optimize Etme

Adlı verilen değer kümesi

Tüm değerlere ad verme

NumericVector x = NumericVector::create( 
    _["a"] = 1, _["b"] = 2, _["c"] = 3
) ;

Bazı değerlere ad verme

IntegerVector y = IntegerVector::create( 
    _["d"] = 4, 5, 6, _["f"] = 7
) ;
Rcpp ile R Kodunu Optimize Etme

Vektör klonlama

// [[Rcpp::export]]
NumericVector positives( NumericVector x ){

    // x'i y'ye klonla
    NumericVector y = clone(x) ;

    for( int i=0; i< y.size(); i++){
        if( y[i] < 0 ) y[i] = 0 ;
    }
    return y ;
}
Rcpp ile R Kodunu Optimize Etme

Hadi pratik yapalım!

Rcpp ile R Kodunu Optimize Etme

Preparing Video For Download...