Sugar Functions head and tail

Ross Bennett — written Jan 1, 2013 — source

The R functions head and tail return the first (last) n elements of the input vector. With Rcpp sugar, the functions head and tail work the same way as they do in R.

Here we use std::sort from the STL and then tail to return the top n items (items with the highest values) of the input vector.

#include <Rcpp.h>
using namespace Rcpp;
 
// [[Rcpp::export]]
NumericVector top_n(NumericVector y, int n){
    NumericVector x = clone(y);
    std::sort(x.begin(), x.end());	// sort x in ascending order
    return tail(x, n);
}

A simple illustration:

set.seed(42)
x <- rnorm(10)
x
 [1]  1.37096 -0.56470  0.36313  0.63286  0.40427 -0.10612  1.51152
 [8] -0.09466  2.01842 -0.06271
top_n(x, 3)
[1] 1.371 1.512 2.018

Here we use std::sort from the STL and then head to return the bottom n items (items with the lowest values) of the input vector.

// [[Rcpp::export]]
NumericVector bottom_n(NumericVector y, int n){
    NumericVector x = clone(y);
    std::sort(x.begin(), x.end());	// sort x in ascending order
    return head(x, n);
}
bottom_n(x, 3)
[1] -0.56470 -0.10612 -0.09466

tags: sugar  stl 

Related Articles