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

Mol*_*acy 4 r vector

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

# 1.create queue

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

# 2.move Patricia to be in front of Steve

???
Run Code Online (Sandbox Code Playgroud)

我是R的初学者,所以让你的回答尽可能简单,尽可能淡化!谢谢!

A5C*_*2T1 11

我的moveMe功能(在我的SOfun包中)非常适合这个.加载包后,您可以执行以下操作:

library(SOfun)
queue <- c("James", "Mary", "Steve", "Alex", "Patricia")
moveMe(queue, "Patricia before Steve")
# [1] "James"    "Mary"     "Patricia" "Steve"    "Alex"  
Run Code Online (Sandbox Code Playgroud)

您还可以通过用分号分隔命令来复合命令:

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" 
Run Code Online (Sandbox Code Playgroud)

移动选项包括:"第一","最后","之前"和"之后".

您还可以通过逗号分隔多个值来移动到某个位置.例如,要在"Mary"之前移动"Patricia"和"Alex"(按此顺序重新排序)然后将"Steve"移动到队列的开头,您将使用:

moveMe(queue, "Patricia, Alex before Mary; Steve first")
# [1] "Steve"    "James"    "Patricia" "Alex"     "Mary"  
Run Code Online (Sandbox Code Playgroud)

您可以安装SOfun:

library(devtools)
install_github("SOfun", "mrdwab")
Run Code Online (Sandbox Code Playgroud)

对于单个值,在另一个值之前移动,您还可以采用如下方法:

## 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" 
Run Code Online (Sandbox Code Playgroud)

  • “ *注定是您在R会话中加载的最重要的R包。*”-喜欢它。 (2认同)
  • @thelatemail,这不是事实吗:-) (2认同)

Wil*_*son 7

实现此目的的一种方法是:

queue <- queue[c(1,2,5,3,4)]
Run Code Online (Sandbox Code Playgroud)

但这是手动的,不是很通用。基本上,您通过说出如何对当前索引重新排序来对向量进行重新排序。

如果要按字母顺序对队列进行排序(这确实会使Patricia位于Steve的前面):

queue <- sort(queue)
Run Code Online (Sandbox Code Playgroud)