如何颠倒向量中每两个连续元素的顺序?

huangapple go评论104阅读模式
英文:

How to reverse the order of each two consecutive elements in a vector?

问题

我想要反转每两个连续元素的顺序,如下所示:

2 1 4 3 6 5
英文:

Let's say I have the following vector

x = c(1,2,3,4,5,6)

I wish to reverse the order of each two consecutive elements as follows

2 1 4 3 6 5

答案1

得分: 3

这是一个想法,

c(rbind(x[c(FALSE, TRUE)], x[c(TRUE, FALSE)]))
# [1] 2 1 4 3 6 5
英文:

Here is an idea,

c(rbind(x[c(FALSE, TRUE)], x[c(TRUE, FALSE)]))
# [1] 2 1 4 3 6 5

答案2

得分: 3

你也可以这样做:

as.vector(matrix(x, nrow = 2)[2:1, ])

[1] 2 1 4 3 6 5
英文:

You could also do

as.vector(matrix(x, nrow = 2)[2:1, ])

[1] 2 1 4 3 6 5

答案3

得分: 3

另一种可能性:

x[seq_along(x) + c(1, -1)]
# [1] 2 1 4 3 6 5
英文:

Another possibility:

x[seq_along(x) + c(1, -1)]
# [1] 2 1 4 3 6 5

答案4

得分: 2

你可以使用 ave + rev 来按组反转向量:

ave(x, (seq_along(x) + 1) %/% 2, FUN = rev)
#[1] 2 1 4 3 6 5
英文:

You can use ave + rev to reverse the vector by group:

ave(x, (seq_along(x) + 1) %/% 2, FUN = rev)
#[1] 2 1 4 3 6 5

huangapple
  • 本文由 发表于 2023年7月31日 21:16:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定