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

时间:2014-09-09 01:01:27

标签: r vector

我有一个元素在某一行中的向量,但现在我想改变这些元素的顺序。我怎么能只用一行代码呢?

# 1.create queue

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

# 2.move Patricia to be in front of Steve

???

我是R的初学者,所以尽量让你的回答变得简单和淡化!谢谢!

3 个答案:

答案 0 :(得分:10)

我的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" 

移动选项包括:&#34;第一个&#34;,&#34;最后&#34;,&#34;在&#34;之前和#34;在#34;之后。

您还可以通过用逗号分隔多个值来移动到某个位置。例如,移动&#34; Patricia&#34;和#34; Alex&#34;之前&#34; Mary&#34; (按顺序重新排序)然后移动&#34;史蒂夫&#34;到队列的开头,你会使用:

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" 

答案 1 :(得分:5)

实现这一目标的一种方法是:

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

但那本手册并不是很普遍。基本上,您通过说明如何重新排序当前索引来重新排序向量。

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

queue <- sort(queue)

答案 2 :(得分:-3)

我认为你打算让它更优雅,但你的问题并没有详细说明。但是为了简单起见,只需重写queue的定义。

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