问题描述:

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!

网友答案:

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)

If neither of these answers suit your needs, you should update your question with the constraints you have.

网友答案:

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" 
网友答案:

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")
相关阅读:
Top