Optimiser le code R avec Rcpp
Romain François
Consulting Datactive, ThinkR
Vecteurs Rcpp
Vecteurs STL
Code R vectorisé
extract_positives <- function(x){
x[x>0]}
Code inefficace qui agrandit un vecteur dans une boucle
extract_positives_loop <- function(x){
y <- numeric()
for( value in x){
if( value > 0 ){
y <- c(x, y)} }
y
}
NumericVector x ;
int n = x.size() ;
int np = 0 ;
for( int i=0 ; i<n ; i++ ){
if( ___ ){
np++ ;
}
}
NumericVector result(np) ;
for( int i=0, j=0 ; i<n ; i++ ){
if( ___ ){
result[j++] = x[i] ;
}
}
// [[Rcpp::export]]
std::vector<double> positives_stl( NumericVector x ){
std::vector<double> out ;
out.reserve( x.size() / 2 ) ;
for( ___ ; ___ ; ___ ){
if( ___ ){
out.push_back(___) ;
}
}
return out ;
}
Optimiser le code R avec Rcpp