加重平均

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

Romain François

Consulting Datactive, ThinkR

xの重みwによる加重平均

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

Rバージョン

# see also ?weighted.mean
weighted_mean_R <- function(x, w){
    sum(x*w) / sum(w)
}

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

Rバージョン

# see also ?weighted.mean
weighted_mean_R <- function(x, w){
    sum(x*w) / sum(w)
}

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

Rバージョン

# see also ?weighted.mean
weighted_mean_R <- function(x, w){
    sum(x*w) / sum(w)
}

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

Rバージョン

# see also ?weighted.mean
weighted_mean_R <- function(x, w){
    sum(x*w) / sum(w)
}

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

非効率なRバージョン

weighted_mean_loop <- function(x, w){
    total_xw <- 0
    total_w  <- 0

    for( i in seq_along(x)){
        total_xw <- total_xw + x[i]*w[i]
        total_w  <- total_w  + w[i]
    }

    total_xw / total_w

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

C++バージョンの骨格

// [[Rcpp::export]]
double weighted_mean_cpp( NumericVector x, NumericVector w){
    double total_xw = 0.0 ;
    double total_w  = 0.0 ;

    int n = ___ ;

    for( ___ ; ___ ; ___ ){
        // accumulate into total_xw and total_w
    }

    return total_xw / total_w ;

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

欠損値

  • 数値ベクトルで欠損値を判定する
bool test = NumericVector::is_na(x) ;
  • doubleにおけるNAの表現
double y = NumericVector::get_na() ;
Rcpp で R コードを最適化する

さあ、練習しましょう!

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

Preparing Video For Download...