You can make use of head
and tail
to create a function like this:
shifter <- function(x, n = 1) {
if (n == 0) x else c(tail(x, -n), head(x, n))
}
Usage:
a <- 1:4
shifter(a)
# [1] 2 3 4 1
shifter(a, 2)
# [1] 3 4 1 2
(Or, library(SOfun); shifter(a)
where you can get SOfun
from here).