在R中更改向量元素的顺序

10

我有一个向量,其中元素按行排列,但现在我想改变这些元素的顺序。我该如何只用一行代码实现呢?

# 1.create queue

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

# 2.move Patricia to be in front of Steve

???

我是R语言的初学者,希望你们的回答能够简单易懂一些!谢谢!


1
你有进行过任何搜索吗? - IRTFM
2
这是一道作业题吗?如果是的话,你应该在帖子中提到。 - Gregor Thomas
2
在提问之前,您至少应该仔细阅读写得出奇地好的手册。对于您的问题,请参考第2.7节。我建议在提问之前先展示您尝试过的东西,因为没有展示尝试或研究的问题很少会受到良好的回应。 - Will Beason
3个回答

16

我的moveMe函数(在我的SOfun软件包中)非常适合这种情况。一旦加载了该软件包,您可以使用以下命令进行操作:

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" 

3
注定成为您在 R 会话中加载过的最重要的 R 包 - 真棒。 - thelatemail
2
@thelatemail,这不是真的吗 :-) - A5C1D2H2I1M1N2O1R2T1
1
moveMe听起来像是一个很棒的工具!感谢你的建议! - Molly Tracy
1
嵌套append(setfiff)解决了我的问题。 - Chris

12

完成这个任务的一种方法是:

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

但这种方法是手动的,不太通用。基本上,你需要通过说明如何重新排序当前索引来重新排序向量。

如果你想按字母顺序对队列进行排序(这样Patricia就会排在Steve前面):

queue <- sort(queue)

1
我的回答的结尾,我提供了一个替代方案,展示了setdiffappend在这里如何有用。 - A5C1D2H2I1M1N2O1R2T1

-4

我认为你的意图是让这更加优雅,但是你的问题并没有具体说明如何做到。不过为了简单起见,只需重新编写queue的定义即可。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接