Tworzenie wektorów

Optymalizacja kodu R za pomocą Rcpp

Romain François

Consulting Datactive, ThinkR

Pobieranie wektora ze strony R

Kod C++

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

Wywołanie z R

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

x[1]
13.2

13.2
Optymalizacja kodu R za pomocą Rcpp
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

Kilka przypadków

# x is already a numeric vector
extract( c(13.3, 54.2), 0 )
13.3
# x is an integer vector, it is first coerced to a numeric vector
extract( 1:10, 0 )
1
Optymalizacja kodu R za pomocą Rcpp
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}
# conversion not possible: error
extract( letters, 0 )
Error in extract(letters, 0) : 
  Not compatible with requested type: [type=character; target=double].
Optymalizacja kodu R za pomocą Rcpp

Tworzenie wektora o zadanym rozmiarze

// [[Rcpp::export]]
NumericVector ones(int n){
    // create a new numeric vector of size n
    NumericVector x(n) ;    
    // manipulate it
    for( int i=0; i<n; i++){
        x[i] = 1 ; }
    return x ;
}

Wywołanie ones z R:

ones(10)
1 1 1 1 1 1 1 1 1 1
Optymalizacja kodu R za pomocą Rcpp

Warianty konstruktora

double value = 42.0 ;
int n = 20 ;

// create a numeric vector of size 20 
// with all values set to 42
NumericVector x( n, value ) ;

Optymalizacja kodu R za pomocą Rcpp

Zadany zestaw wartości

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

CharacterVector s = CharacterVector::create( "pink", "blue" );
Optymalizacja kodu R za pomocą Rcpp

Zadany zestaw wartości z nazwami

Nazwy dla wszystkich wartości

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

Nazwy dla wybranych wartości

IntegerVector y = IntegerVector::create( 
    _["d"] = 4, 5, 6, _["f"] = 7
) ;
Optymalizacja kodu R za pomocą Rcpp

Klonowanie wektorów

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

    // clone x into y
    NumericVector y = clone(x) ;

    for( int i=0; i< y.size(); i++){
        if( y[i] < 0 ) y[i] = 0 ;
    }
    return y ;
}
Optymalizacja kodu R za pomocą Rcpp

Czas na ćwiczenia!

Optymalizacja kodu R za pomocą Rcpp

Preparing Video For Download...