Circular variable arrays in R at distance n

Say I have

a <- c(1, 2, 3)

and I want b to be obtained from a by moving it to the left by a distance of 1

b
# [1] 2 3 1

By derivation, I also mean:

  • Pass "a" to a function that spits out "b"
  • You are using some kind of index short that does this.
  • b <- c(2, 3, 1), for example, is not the solution I'm looking for.

What would be elegant / effective ways to do this?

+4
source share
1 answer

You can use headand tailto create such a function:

shifter <- function(x, n = 1) {
  if (n == 0) x else c(tail(x, -n), head(x, n))
}

Using:

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 SOfunfrom here ).

+12
source

All Articles