January 1, 2013
By

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

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
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
}
``````
``````bottom_n(x, 3)
``````
```[1] -0.56470 -0.10612 -0.09466
```

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...