建立向量

用 Rcpp 最佳化 R 程式碼

Romain François

Consulting Datactive, ThinkR

從 R 端取得向量

C++ 程式碼

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

從 R 呼叫

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

x[1]
13.2

13.2
用 Rcpp 最佳化 R 程式碼
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

多種情況

# x 已是 numeric 向量
extract( c(13.3, 54.2), 0 )
13.3
# x 是 integer 向量,會先轉為 numeric 向量
extract( 1:10, 0 )
1
用 Rcpp 最佳化 R 程式碼
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}
# 無法轉換:發生錯誤
extract( letters, 0 )
Error in extract(letters, 0) : 
  Not compatible with requested type: [type=character; target=double].
用 Rcpp 最佳化 R 程式碼

建立指定大小的向量

// [[Rcpp::export]]
NumericVector ones(int n){
    // 建立大小為 n 的 numeric 向量
    NumericVector x(n) ;    
    // 指定內容
    for( int i=0; i<n; i++){
        x[i] = 1 ; }
    return x ;
}

從 R 呼叫 ones

ones(10)
1 1 1 1 1 1 1 1 1 1
用 Rcpp 最佳化 R 程式碼

建構子變體

double value = 42.0 ;
int n = 20 ;

// 建立大小為 20 的 numeric 向量
// 並將所有值設為 42
NumericVector x( n, value ) ;

用 Rcpp 最佳化 R 程式碼

給定一組值

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

CharacterVector s = CharacterVector::create( "pink", "blue" );
用 Rcpp 最佳化 R 程式碼

具名的給定值

為所有值命名

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

只為部分值命名

IntegerVector y = IntegerVector::create( 
    _["d"] = 4, 5, 6, _["f"] = 7
) ;
用 Rcpp 最佳化 R 程式碼

向量複製

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

    // 將 x 複製到 y
    NumericVector y = clone(x) ;

    for( int i=0; i< y.size(); i++){
        if( y[i] < 0 ) y[i] = 0 ;
    }
    return y ;
}
用 Rcpp 最佳化 R 程式碼

一起來練習吧!

用 Rcpp 最佳化 R 程式碼

Preparing Video For Download...