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