我的moveMe function(my SOfun package)非常适合这个。一旦包被加载,你可以做你想做的事:
library(SOfun)
queue <- c("James", "Mary", "Steve", "Alex", "Patricia")
moveMe(queue, "Patricia before Steve")
# [1] "James" "Mary" "Patricia" "Steve" "Alex"
您还可以通过用分号分隔命令来复合命令:
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"
移动选项包括:“first”、“last”、“before”和“after”。
您还可以通过逗号分隔多个值来将它们移动到一个位置。例如,要将“Patricia”和“Alex”移动到“Mary”之前(按该顺序重新排序),然后将“Steve”移动到队列的开头,您可以使用:
moveMe(queue, "Patricia, Alex before Mary; Steve first")
# [1] "Steve" "James" "Patricia" "Alex" "Mary"
您可以通过以下方式安装 SOfun:
library(devtools)
install_github("SOfun", "mrdwab")
对于单个值,在另一个值之前移动,您还可以采用如下方法:
## 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"