Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Last active November 17, 2017 08:01
Show Gist options
  • Save romainfrancois/b5f14c8f066599c826d5266e166d19d8 to your computer and use it in GitHub Desktop.
Save romainfrancois/b5f14c8f066599c826d5266e166d19d8 to your computer and use it in GitHub Desktop.
#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)
)
*/
@romainfrancois
Copy link
Author

> # move the first 4 letters at the end
> rotate( letters, 4)
 [1] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "a" "b" "c" "d"
> # move the (n-2) first letters at the end
> rotate( letters, -2)
 [1] "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x"
> 
> 
> friends <- c("Rachel", "Monica", "Phoebe", "Ross", "Chandler", "Joey" )
> tibble( 
+     name = sample(friends), 
+     partner = rotate(name, 1)
+ )
# A tibble: 6 x 2
      name  partner
     <chr>    <chr>
1     Ross     Joey
2     Joey   Monica
3   Monica   Rachel
4   Rachel Chandler
5 Chandler   Phoebe
6   Phoebe     Ross

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment