Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move element from front of array to back of array in R

Tags:

r

Is there an elegant way to take a vector like

x = c("a", "b", "c", "d", "e")

and make it be

x = c("b", "c", "d", "e", "a")

I did:

x = c("a", "b", "c", "d", "e")
firstVal = x[1]
x = tail(x,-1)
x[length(x)+1] = firstVal
x
[1] "b" "c" "d" "e" "a"

It works, but kinda ugly.

like image 285
Micro Avatar asked Apr 29 '14 16:04

Micro


2 Answers

Elegance is a matter of taste, and de gustibus non est disputandum:

> x <- c("a", "b", "c", "d", "e")
> c(x[-1], x[1])
[1] "b" "c" "d" "e" "a"

Does the above make you happy? :)

like image 108
gagolews Avatar answered Oct 21 '22 22:10

gagolews


Overkill time: You can consider my shifter or my moveMe function, both of which are part of my GitHub-only SOfun package.

Here are the relevant examples:

shifter

This is basically a head and tail approach:

## Specify how many values need to be shifted
shifter(x, 1)
# [1] "b" "c" "d" "e" "a"
shifter(x, 2)
# [1] "c" "d" "e" "a" "b"

## The direction can be changed too :-)
shifter(x, -1)
# [1] "e" "a" "b" "c" "d"

moveMe

This is fun:

moveMe(x, "a last")
# [1] "b" "c" "d" "e" "a"

## Lots of options to move things around :-)
moveMe(x, "a after d; c first")
# [1] "c" "b" "d" "a" "e"
like image 38
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 21 '22 21:10

A5C1D2H2I1M1N2O1R2T1