Last active
November 17, 2017 08:01
-
-
Save romainfrancois/b5f14c8f066599c826d5266e166d19d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Rcpp.h> | |
using namespace Rcpp ; | |
// [[Rcpp::plugins(cpp11)]] | |
template <int RTYPE> | |
Vector<RTYPE> rotate_impl( Vector<RTYPE> x, int pivot ){ | |
auto n = x.size() ; | |
Vector<RTYPE> res = no_init(n) ; | |
// similar to wjat head and tail do, if pivot is | |
// negative, interpret it as counting from | |
if( pivot < 0 ){ | |
pivot = n + pivot ; | |
} | |
// copy the last elements of x into the start of res | |
auto it = std::copy( | |
x.begin() + pivot , | |
x.end(), | |
res.begin() | |
) ; | |
// and then the first elements | |
std::copy( x.begin(), x.begin() + pivot , it) ; | |
return res ; | |
} | |
// [[Rcpp::export]] | |
SEXP rotate( SEXP x, int pivot ){ | |
RCPP_RETURN_VECTOR(rotate_impl, x, pivot ) ; | |
} | |
/*** R | |
# move the first 4 letters at the end | |
rotate( letters, 4) | |
# move the (n-2) first letters at the end | |
rotate( letters, -2) | |
friends <- c("Rachel", "Monica", "Phoebe", "Ross", "Chandler", "Joey" ) | |
tibble( | |
name = sample(friends), | |
partner = rotate(name, 1) | |
) | |
*/ |
Author
romainfrancois
commented
Nov 17, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment