简体   繁体   中英

Change the order of elements in vector in R

I have a vector with elements in a certain row, but now I want to change the order of these elements. How can I do this with only one line of code?

# 1.create queue

queue <- c("James", "Mary", "Steve", "Alex", "Patricia")
queue

# 2.move Patricia to be in front of Steve

???

I am a beginner at R so make your responses as simple and watered down as possible! Thanks!

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)

I think you intend for this to be more elegant, but your question doesn't specify how. For simplicity though, just rewrite the definition of queue .

queue <- c("James", "Mary", "Patricia", "Steve", "Alex")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM