Predictive Hacks

How to Circular Shift Vectors in R

We have provided a tip of how to circular shift lists in Python. Let’s see how we can do it in R by building our custom function.

custom_roll <- function( x , n ){
  if( n == 0 | n%%length(x)==0) {
    return(x)
    }
  
  else if (abs(n)>length(x)) {
  new_n<- (abs(n)%%length(x))*sign(n)
  return(c( tail(x,new_n) , head(x,-new_n) ))
  }
  else {
  return(c( tail(x,n) , head(x,-n) ))
  }
}

Let’s see what we get but taking into consideration the vector (1,2,3,4,5).

x<-c(1,2,3,4,5)
custom_roll(x,-11)
[1] 2 3 4 5 1

Or:

x<-c(1,2,3,4,5)
custom_roll(x,12)
[1] 4 5 1 2 3

Or a simpler example:

x<-c(1,2,3,4,5)
custom_roll(x,1)
[1] 5 1 2 3 4

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s