Change the order of elements in vector in R

My moveMe function (in my SOfun package) is perfect for this. Once the package is loaded, you can do what you want with:

library(SOfun)
queue <- c("James", "Mary", "Steve", "Alex", "Patricia")
moveMe(queue, "Patricia before Steve")
# [1] "James"    "Mary"     "Patricia" "Steve"    "Alex"  

You can also compound commands by separating them with semicolons:

moveMe(queue, "Patricia before Steve; James last")
# [1] "Mary"     "Patricia" "Steve"    "Alex"     "James" 

moveMe(queue, "Patricia before Steve; James last; Mary after Alex")
# [1] "Patricia" "Steve"    "Alex"     "Mary"     "James" 

Options for moving include: "first", "last", "before", and "after".

You can also move multiple values to a position by separating them by commas. For instance, to move "Patricia" and "Alex" before "Mary" (reordered in that order) and then move "Steve" to the start of the queue, you would use:

moveMe(queue, "Patricia, Alex before Mary; Steve first")
# [1] "Steve"    "James"    "Patricia" "Alex"     "Mary"  

You can install SOfun with:

library(devtools)
install_github("SOfun", "mrdwab")

For a single value, moved before another value, you could also take an approach like the following:

## Create a vector without "Patricia"
x <- setdiff(queue, "Patricia")
## Use `match` to find the point at which to insert "Patricia"
## Use `append` to insert "Patricia" at the relevant point
x <- append(x, values = "Patricia", after = match("Steve", x) - 1)
x
# [1] "James"    "Mary"     "Patricia" "Steve"    "Alex" 

One way to accomplish this is:

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

But that's manual and not very generalizable. Basically, you reorder the vector by saying how to reorder the current indexes.

If you want to sort the queue alphabetically (which does cause Patricia to be in front of Steve):

queue <- sort(queue)

Tags:

R

Vector