gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:57:10 24 4
gpt4 key购买 nike

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

# 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com