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

标签 r vector

我有一个包含某行元素的向量,但现在我想更改这些元素的顺序。我怎样才能只用一行代码做到这一点?

# 1.create queue

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

# 2.move Patricia to be in front of Steve

???

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

最佳答案

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

关于r - 更改 R 中向量中元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735261/

相关文章:

ios - iOS 中的世界地图

c++ - 将二维 vector 转换为二维数组

Python/Pygame : 2d angular momentum/inertia

c++ - 我有一个基类对象和派生类对象的 vector ,但我无法访问存储在 vector 中的派生对象继承的数据成员

java - 如何在Java中存储 vector ?数据类型是什么?

r - 在rentrez中使用entrez_fetch解析PubMed XML

bash - R 中 system() 的替代方法,用于调用 sed、rsync、ssh 等。: Do functions exist, 我应该自己编写,还是我错过了重点?

R Shiny : conditionalPanel with condition based on textInput (how to)

r - ggplot2 代码运行并更新绘图,但实际上没有显示数据

r - purrr 使用模型到数据