加權平均

用 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...