Viktat medelvärde

Optimera R-kod med Rcpp

Romain François

Consulting Datactive, ThinkR

Viktat medelvärde av x med vikter w

Optimera R-kod med Rcpp

R-version

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

Optimera R-kod med Rcpp

R-version

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

Optimera R-kod med Rcpp

R-version

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

Optimera R-kod med Rcpp

R-version

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

Optimera R-kod med Rcpp

Ineffektiv R-version

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

}
Optimera R-kod med Rcpp

Skelett för en C++-version

// [[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 ;

}
Optimera R-kod med Rcpp

Saknade värden

  • Testa om ett värde saknas i en numerisk vektor
bool test = NumericVector::is_na(x) ;
  • Representationen av NA i double
double y = NumericVector::get_na() ;
Optimera R-kod med Rcpp

Nu kör vi en övning!

Optimera R-kod med Rcpp

Preparing Video For Download...