Say I have
a <- c(1, 2, 3)
and I want b to be derived from a by shifting it in direction "left" by distance 1
b
# [1] 2 3 1
By derivation I mean you either:
b <- c(2, 3, 1)
, for example, is not a solution I'm looking forWhat would be elegant/efficient ways to do that?
Circular shift can be of two types – Left circular shift (moving the final bit to the first position, while shifting all other bits to the next position). Right circular shift (moving the first bit to the last position, while shifting all other bits to the previous position). For example, Input: N = 127 (00000000000000000000000001111111) shift = 3
Y = circshift (A,K,dim) circularly shifts the values in array A by K positions along dimension dim. Inputs K and dim must be scalars. Create a numeric column vector. Use circshift to shift the elements by three positions. The result, Y, has the same elements as A but they are in a different order.
A circular shift is a special kind of cyclic permutation, which in turn is a special kind of permutation. Formally, a circular shift is a permutation σ of the n entries in the tuple such that either modulo n, for all entries i = 1, ..., n.
This syntax specifies 1 as the dimension to operate along. Y = circshift (A,K,dim) circularly shifts the values in array A by K positions along dimension dim. Inputs K and dim must be scalars.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With