Ağırlıklı ortalama

Rcpp ile R Kodunu Optimize Etme

Romain François

Consulting Datactive, ThinkR

x'in w ağırlıklarıyla ağırlıklı ortalaması

Rcpp ile R Kodunu Optimize Etme

R sürümü

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

Rcpp ile R Kodunu Optimize Etme

R sürümü

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

Rcpp ile R Kodunu Optimize Etme

R sürümü

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

Rcpp ile R Kodunu Optimize Etme

R sürümü

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

Rcpp ile R Kodunu Optimize Etme

Verimsiz R sürümü

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 ile R Kodunu Optimize Etme

C++ sürümünün iskeleti

// [[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 ile R Kodunu Optimize Etme

Eksik değerler

  • Sayısal bir vektörde değerin eksik olup olmadığını test etme
bool test = NumericVector::is_na(x) ;
  • double içinde NA gösterimi
double y = NumericVector::get_na() ;
Rcpp ile R Kodunu Optimize Etme

Hadi pratik yapalım!

Rcpp ile R Kodunu Optimize Etme

Preparing Video For Download...