가중 평균

Rcpp로 R 코드 최적화하기

Romain François

Consulting Datactive, ThinkR

가중치 w를 적용한 x의 가중 평균

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