【问题标题】:Change the order of elements in vector in R在R中更改向量中元素的顺序
【发布时间】:2014-09-09 01:01:26
【问题描述】:

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

# 1.create queue

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

# 2.move Patricia to be in front of Steve

???

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

【问题讨论】:

  • 你搜索过吗?
  • 这是作业题吗?如果是这样,您应该在帖子中提及它。
  • 在提问之前您至少应该look through the surprisingly well-written manual。对于您的问题,请参阅第 2.7 节。我建议在提问之前向我们展示您尝试过的东西,因为没有尝试或研究过的问题很少受到欢迎。

标签: r vector


【解决方案1】:

我的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 包。" - 喜欢它。
  • @thelatemail,这不是真的吗:-)
  • moveMe 听起来是个很棒的工具!感谢您的提示!
  • 嵌套append(setfiff 解决了我的问题。
【解决方案2】:

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

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

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

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

queue <- sort(queue)

【讨论】:

  • 在my answer 的末尾,我提出了一个替代方案,说明setdiff 和append 在这里如何发挥作用。
【解决方案3】:

我认为你打算让它更优雅,但你的问题没有具体说明如何。不过为简单起见,只需重写queue 的定义即可。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多