Sugar Functions head and tail

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)