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.
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? :)
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"
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