Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular shift of vector by distance n [duplicate]

Tags:

r

vector

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:

  1. Pass "a" into a function that spits out "b"
  2. You use some sort of indexing short had which does that.
  3. b <- c(2, 3, 1), for example, is not a solution I'm looking for

What would be elegant/efficient ways to do that?

like image 927
user1172468 Avatar asked May 30 '15 04:05

user1172468


People also ask

What is circular shift?

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

How do you do a circular shift in MATLAB?

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.

What is a circular shift in Python?

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.

How to circularly shift values in an array along dimension dim?

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.


1 Answers

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

like image 195
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 30 '22 00:10

A5C1D2H2I1M1N2O1R2T1